/**
* double checked locking
*/
public class Singleton {
private Singleton() {
}
private static volatile Singleton instance = null;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
为甚么这样做?
避免synchronized 内过多代码块,从而影响效率。
为甚么要加volatile?
避免指令重排从而影响到代码准确性。