use*_*756 1 java algorithm concurrency synchronization
让我们看看经典的双重检查
class Foo {
private volatile Foo singleton = null;
public Foo getFooSingleton() {
if (singleton == null) {
synchronized(this) {
if (singleton == null)
singleton = new Foo();
}
}
return singleton;
}
}
Run Code Online (Sandbox Code Playgroud)
易失性modifire保证在所有线程中都能正确看到"singleton"变量的值.但在当前的例子中我真的需要这个吗?我想不是.所以 - 这就是我看到这个程序以最糟糕的方式运行的方式 - 当一个线程所做的更改被其他人看不到时.
singleton != null),进行第二次检查并退出同步部分.所以.即使没有挥发性声明,一切都有效,甚至更好=)