public class Singleton { private static class InstanceHolder { static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return InstanceHolder.INSTANCE; } private Singleton() {} }
这会INSTANCE在第一次调用时初始化变量,从而利用该语言的线程安全保证进行静态初始化,而无需进行额外的同步。Singleton.getInstance()
此实现也称为Bill Pugh单例模式。[Wiki]