單例模式
/**
* @description:
* 單例1 懶漢模式 double check
* @author: brave.chen
* @create: 2020-03-07 13:31
**/
public class SingleDecl {
private static SingleDecl singleDecl;
private SingleDecl() {
}
public static SingleDecl getInstance(){
if(singleDecl == null){
synchronized (SingleDecl.class){
if(singleDecl == null){
singleDecl = SingleDecl.getInstance();
}
}
}
return singleDecl;
}
}
上述代碼并不是線程安全的
因為singleDecl = SingleDecl.getInstance();這部分代碼并不是原子性的,
這個操作有很多步
// 創(chuàng)建 Cache 對象實例,分配內(nèi)存
0: new #5 // class com/query/Cache
// 復(fù)制棧頂?shù)刂罚⒃賹⑵鋲喝霔m? 3: dup
// 調(diào)用構(gòu)造器方法,初始化 Cache 對象
4: invokespecial #6 // Method "<init>":()V
// 存入局部方法變量表
7: astore_1

時序圖
如果遇到這種情況 那么線程2就會返回null。
如何解決
/**
* @description:
* 單例1 懶漢模式 double check
* @author: brave.chen
* @create: 2020-03-07 13:31
**/
public class SingleDecl {
private volatile static SingleDecl singleDecl;
private SingleDecl() {
}
public static SingleDecl getInstance(){
if(singleDecl == null){
synchronized (SingleDecl.class){
if(singleDecl == null){
singleDecl = SingleDecl.getInstance();
}
}
}
return singleDecl;
}
}
加了 volatile 關(guān)鍵字后
volatile 作用
正確的雙重檢查鎖定模式需要需要使用 volatile。volatile主要包含兩個功能。
保證可見性。使用 volatile 定義的變量,將會保證對所有線程的可見性。
禁止指令重排序優(yōu)化。
由于 volatile 禁止對象創(chuàng)建時指令之間重排序,所以其他線程不會訪問到一個未初始化的對象,從而保證安全性。
注意,volatile禁止指令重排序在 JDK 5 之后才被修復(fù)