我在Java中看到一些示例,在代码块上进行同步以更改某些变量,而该变量最初被声明为volatile。我在一个单例类的示例中看到了这个,他们将唯一实例声明为volatile,并且在初始化该实例的代码块上同步...我的问题是为什么我们要声明它为volatile,同时对它进行同步?难道其中一个不足以代替另一个吗?
public class SomeClass {
volatile static Object uniqueInstance = null;
public static Object getInstance() {
if (uniqueInstance == null) {
synchronized (someClass.class) {
if (uniqueInstance == null) {
uniqueInstance = new SomeClass();
}
}
}
return uniqueInstance;
}
}
提前感谢。