主要有三個(gè)版本,第三個(gè)版本是最優(yōu)答案。
volatile關(guān)鍵字不但可以防止指令重排,也可以保證線程訪問的變量值是主內(nèi)存中的最新值。
第一版 線程不安全
public class Singleton {
private Singleton() {} //私有構(gòu)造函數(shù)
private static Singleton instance = null; //單例對象
//靜態(tài)工廠方法
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
第二版 有漏洞
public class Singleton {
private Singleton() {} //私有構(gòu)造函數(shù)
private static Singleton instance = null; //單例對象
//靜態(tài)工廠方法
public static Singleton getInstance() {
if (instance == null) { //雙重檢測機(jī)制
synchronized (Singleton.class){ //同步鎖
if (instance == null) { //雙重檢測機(jī)制
instance = new Singleton();
}
}
}
return instance;
}
}
第三版 最優(yōu)解
public class Singleton {
private Singleton() {} //私有構(gòu)造函數(shù)
private volatile static Singleton instance = null; //單例對象
//靜態(tài)工廠方法
public static Singleton getInstance() {
if (instance == null) { //雙重檢測機(jī)制
synchronized (this){ //同步鎖
if (instance == null) { //雙重檢測機(jī)制
instance = new Singleton();
}
}
}
return instance;
}
}