我正在阅读有关单身人士的内容,并且不明白为什么会这样做
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
比这个
更有效率public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
return instance;
}
答案 0 :(得分:1)
第一种模式可以为您节省麻烦和性能,并节省开销。检查null
- 类加载器应该确保该类只加载并初始化一次。