雙重檢查鎖定失敗可能性
雙重檢查鎖定在延遲初始化的單例模式中見得比較多(單例模式實現(xiàn)方式很多,這里為說明雙重檢查鎖定問題,只選取這一種方式),先來看一個版本:
- public class Singleton {
- private static Singleton instance = null;
- private Singleton(){}
- public static Singleton getInstance() {
- if(instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
上面是最原始的模式,一眼就可以看出,在多線程環(huán)境下,可能會產(chǎn)生多個Singleton實例,于是有了其同步的版本:
- public class Singleton {
- private static Singleton instance = null;
- private Singleton(){}
- public synchronized static Singleton getInstance() {
- if(instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
在這個版本中,每次調(diào)用getInstance都需要取得Singleton.class上的鎖,然而該鎖只是在開始構(gòu)建Singleton 對象的時候才是必要的,后續(xù)的多線程訪問,效率會降低,于是有了接下來的版本:
- public class Singleton {
- private static Singleton instance = null;
- private Singleton(){}
- public static Singleton getInstance() {
- if(instance == null) {
- synchronized(Singleton.class) {
- if(instance == null) {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
- }
很好的想法!不幸的是,該方案也未能解決問題之根本:
原因在于:初始化Singleton 和 將對象地址寫到instance字段 的順序是不確定的。在某個線程new Singleton()時,在構(gòu)造方法被調(diào)用之前,就為該對象分配了內(nèi)存空間并將對象的字段設(shè)置為默認(rèn)值。此時就可以將分配的內(nèi)存地址賦值給instance字段了,然而該對象可能還沒有初始化;此時若另外一個線程來調(diào)用getInstance,取到的就是狀態(tài)不正確的對象。
鑒于以上原因,有人可能提出下列解決方案:
- public class Singleton {
- private static Singleton instance = null;
- private Singleton(){}
- public static Singleton getInstance() {
- if(instance == null) {
- Singleton temp;
- synchronized(Singleton.class) {
- temp = instance;
- if(temp == null) {
- synchronized(Singleton.class) {
- temp = new Singleton();
- }
- instance = temp;
- }
- }
- }
- return instance;
- }
- }
該方案將Singleton對象的構(gòu)造置于最里面的同步塊,這種思想是在退出該同步塊時設(shè)置一個內(nèi)存屏障,以阻止初始化Singleton 和 將對象地址寫到instance字段 的重新排序。
不幸的是,這種想法也是錯誤的,同步的規(guī)則不是這樣的。退出監(jiān)視器(退出同步)的規(guī)則是:所以在退出監(jiān)視器前面的動作都必須在釋放監(jiān)視器之前完成。然而,并沒有規(guī)定說退出監(jiān)視器之后的動作不能放到退出監(jiān)視器之前完成。也就是說同步塊里的代碼必須在退出同步時完成,而同步塊后面的代碼則可以被編譯器或運(yùn)行時環(huán)境移到同步塊中執(zhí)行。
編譯器可以合法的,也是合理的,將instance = temp移動到最里層的同步塊內(nèi),這樣就出現(xiàn)了上個版本同樣的問題。
在JDK1.5及其后續(xù)版本中,擴(kuò)充了volatile語義,系統(tǒng)將不允許對 寫入一個volatile變量的操作與其之前的任何讀寫操作 重新排序,也不允許將 讀取一個volatile變量的操作與其之后的任何讀寫操作 重新排序。
在jdk1.5及其后的版本中,可以將instance 設(shè)置成volatile以讓雙重檢查鎖定生效,如下:
- public class Singleton {
- private static volatile Singleton instance = null;
- private Singleton(){}
- public static Singleton getInstance() {
- if(instance == null) {
- synchronized(Singleton.class) {
- if(instance == null) {
- instance = new Singleton();
- }
- }
- }
- return instance;
- }
- }
需要注意的是:在JDK1.4以及之前的版本中,該方式仍然有問題。
【編輯推薦】