最有效的单例模式?

Most efficient singleton pattern?

我正在阅读有关单例的内容,但不明白为什么会这样

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;
}

第一个模式为您省去了检查 null 的麻烦和性能 "overhead" - classloader 应该确保仅加载和初始化 class一次。