双重锁
public final class Singleton {
private static volatile Singleton instance = null; // volatile 防止jvm字节码重排后出现DCL失效问题
private Singleton(){
}
public static Singleton getSingleton(){
if(instance==null){ //避免每次都要进入同步方法,提高效率
synchronized (Singleton.class){
if(instance==null){ //防止其他线程已经实例化
instance = new Singleton();
}
}
}
return instance;
}
}
静态内部类
public class Singleton{
private Singleton(){}
private static class Holer{// 外部类加载时并不需要立即加载内部类,内部类不被加载则不去初始化INSTANCE,故而不占内存
private static SingleTon instance = new SingleTon();
}
public static getSingleton(){
return Holer.instance;
}
}