这是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
}
1、
volatile
保证了uniqueInstance
的修改对各个线程的可见性。2、这是个
static
方法synchronized(this)
肯定是不行的,因为没有this
。再说synchronized(uniqueInstance)
,synchronized
是针对对象而言的,对象都是堆里的对象,但是初始化状态下uniqueInstance
是null
,只是栈里的一个标识,在堆里没有。我试了一下synchronized(null)
会报空指针异常。