精妙的单例类(Singleton)

Effective Java》中给出了一种精妙Singleton的解决方法,充分利用了Java虚拟机的特性

 

 

Java代码   收藏代码
  1. public class Singleton {  
  2.   
  3.     // an inner class holder the uniqueInstance.  
  4.   
  5.     private static class SingletonHolder {  
  6.   
  7.        static final Singleton uniqueInstance = new Singleton();  
  8.   
  9.     }  
  10.   
  11.     private Singleton() {  
  12.   
  13.        // Exists only to defeat instantiation.  
  14.   
  15.     }  
  16.   
  17.     public static Singleton getInstance() {  
  18.   
  19.        return SingletonHolder.uniqueInstance;  
  20.   
  21.     }  
  22.   
  23.     // Other methods...  
  24.   
  25. }  

 

 

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.

你可能感兴趣的:(java,Singleton,虚拟机)