由于java的內(nèi)存模型的原因,在C++中的雙重檢查模型在Java中不可用:
public static Singleton getInstance() {
if(instance==null) {
synchronized(this) {
if(instance==null) {
instance=new Singleton();
}
}
}
return instance;
}假如采用synchronized方法,又會(huì)嚴(yán)重影響性能:
public static synchronized Singleton getInstance() {
if(instance==null) {
instance=new Singleton();
}
return instance;
}如何實(shí)現(xiàn)Lazy Singleton?方法是利用Java的ClassLoader即時(shí)裝載特性,使用一個(gè)SingletonHolder實(shí)現(xiàn):
static class SingletonHolder {
static Singleton instance = new Singleton();
}public static Singleton getInstance() {
return SingletonHolder.instance;
}這里利用Java ClassLoader特性,在第一次加載SingletonHolder的時(shí)候初始化實(shí)例,并且保證了沒(méi)有多線程并發(fā)問(wèn)題。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注