这是head first 设计模式中单例模式第182页的一段代码
public class Singleton {
// 为什么要使用volatile关键字?
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
/* 为什么要使用synchronized (Singleton.class),使用synchronized(this)或者
synchronized(uniqueInstance)不行吗?而且synchronized(uniqueInstance)的效率更加高?*/
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
问题一:为什么要使用volatierle关键字?
问题二:为什么要使用synchronized (Singleton.class),使用synchronized(this),或者synchronized(uniqueInstance)不行吗?而且synchronized(uniqueInstance)的效率更加高?
Stackoverflow上面的答案
public class Foo extends Thread {
private volatile boolean close = false;
public void run() {
while(!close) {
// do work
}
}
public void close() {
close = true;
// interrupt here if needed
}
}
you need volatile because the thread reading close in the while loop is different from the one that calls close(). Without volatile, the thread running the loop may never see the change to close.
static void myMethod() {
synchronized(MyClass.class) {
//code
}
}
is equivalent to
static synchronized void myMethod() {
//code
}
and
void myMethod() {
synchronized(this) {
//code
}
}
is equivalent to
synchronized void myMethod() {
//code
}