本文介绍了使用双锁时使单例实例易变的重点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private volatile static Singleton uniqueInstance
在单身时使用双锁方法进行同步为什么单个实例声明为volatile?我可以在不将其声明为volatile的情况下实现相同的功能吗?
In a singleton when using double lock method for synchronization why is the single instance declared as volatile ? Can I achieve the same functionality without declaring it as volatile ?
推荐答案
没有 volatile
代码在多个线程中无法正常工作。
Without volatile
the code doesn't work correctly with multiple threads.
来自维基百科的:
// Works with acquire/release semantics for volatile
// Broken under Java 1.4 and earlier semantics for volatile
class Foo {
private volatile Helper helper = null;
public Helper getHelper() {
Helper result = helper;
if (result == null) {
synchronized(this) {
result = helper;
if (result == null) {
helper = result = new Helper();
}
}
}
return result;
}
// other functions and members...
}
一般情况下,如果可能的话,你应该避免重复检查锁定,因为很难做到正确,如果你弄错了,很难找到错误。请尝试这种更简单的方法:
In general you should avoid double-check locking if possible, as it is difficult to get right and if you get it wrong it can be difficult to find the error. Try this simpler approach instead:
// Correct lazy initialization in Java
@ThreadSafe
class Foo {
private static class HelperHolder {
public static Helper helper = new Helper();
}
public static Helper getHelper() {
return HelperHolder.helper;
}
}
这篇关于使用双锁时使单例实例易变的重点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!