Effective Java》中给出了一种精妙Singleton的解决方法,充分利用了Java虚拟机的特性
- public class Singleton {
- // an inner class holder the uniqueInstance.
- private static class SingletonHolder {
- static final Singleton uniqueInstance = new Singleton();
- }
- private Singleton() {
- // Exists only to defeat instantiation.
- }
- public static Singleton getInstance() {
- return SingletonHolder.uniqueInstance;
- }
- // Other methods...
- }
When the getInstance method is invoked for the first time, it reads SingletonHolder.uniqueInstance for the first time, causing the SingletonHolder class to get initialized.The beauty of this idiom is that the getInstance method is not synchronized and performs only a field access, so lazy initialization adds practically nothing to the cost of access. A modern VM will synchronize field access only to initialize the class.Once the class is initialized, the VM will patch the code so that subsequent access to the field does not involve any testing or synchronization.