多线程高并发单例模式

时间:2022-04-21 20:46:31

内部类实例化static inner class

/**
* 静态内部类做单例
*
*/

public class Singletion {

private static class InnerSingletion {
private static Singletion single = new Singletion();
}

public static Singletion getInstance(){
return InnerSingletion.single;
}

}

2次检查实例化dubble check instance

public class DubbleSingleton {

private static DubbleSingleton ds;

public static DubbleSingleton getDs(){
if(ds == null){
//【等待位置】
synchronized (DubbleSingleton.class) {
if(ds == null){
//初始化有可能耗时比较长,导致N个线程到达【等待位置】,如果这里不第二次检查ds,就会生成N个新实例对象。
ds = new DubbleSingleton();
}
}
}
return ds;
}
}