Effective Java》中给出了一种精妙Singleton的解决方法,充分利用了Java虚拟机的特性
- publicclassSingleton{
- //aninnerclassholdertheuniqueInstance.
- privatestaticclassSingletonHolder{
- staticfinalSingletonuniqueInstance=newSingleton();
- }
- privateSingleton(){
- //Existsonlytodefeatinstantiation.
- }
- publicstaticSingletongetInstance(){
- returnSingletonHolder.uniqueInstance;
- }
- //Othermethods...
- }
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虚拟机特性实现的懒汉式单例模式,通过静态内部类来持有唯一实例,并确保线程安全及延迟加载。此方法避免了同步带来的开销,仅在首次访问时初始化。

939

被折叠的 条评论
为什么被折叠?



