單例模式中雙重檢查鎖(double checked locking)
源碼位置:org.springframework.boot.convert.ApplicationConversionService.getSharedInstance()轰驳。獲取共享的轉(zhuǎn)換服務(wù)對(duì)象。
說明:單例模式中使用雙重檢查鎖主要使用在多線程環(huán)境中袜蚕,因?yàn)閷?shí)例初始化是采用的懶加載模式抱虐,僅初始化一次。第一次為空判斷,因?yàn)閷?shí)例初始化為空只有一次村生,剩下的訪問到此處都不可能為空,所以避免了加鎖帶來的性能開銷饼丘。如果多個(gè)線程進(jìn)入了第一個(gè)為空判斷趁桃,只要一個(gè)線程會(huì)獲得鎖進(jìn)行實(shí)例化,如果不進(jìn)行第二次為空判斷則等待線程會(huì)再次進(jìn)行實(shí)例化肄鸽,與單例模式只創(chuàng)建一個(gè)對(duì)象不符卫病。
public static ConversionService getSharedInstance() {
ApplicationConversionService sharedInstance = ApplicationConversionService.sharedInstance;
//第一次為空判斷,避免實(shí)例化后進(jìn)入加鎖狀態(tài)的性能開銷
if (sharedInstance == null) {
synchronized (ApplicationConversionService.class) {
sharedInstance = ApplicationConversionService.sharedInstance;
//第二次為空判斷贴捡,避免第一個(gè)線程初始化實(shí)例后忽肛,后續(xù)等待線程再次進(jìn)行實(shí)例化。
if (sharedInstance == null) {
sharedInstance = new ApplicationConversionService();
ApplicationConversionService.sharedInstance = sharedInstance;
}
}
}
return sharedInstance;
}