`
wenjinglian
  • 浏览: 807131 次
  • 性别: Icon_minigender_1
  • 来自: 株洲->深圳
社区版块
存档分类
最新评论

精妙的单例类(Singleton)

    博客分类:
  • JAVA
阅读更多

《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.

 

详见:http://www.uml.org.cn/sjms/201110184.asp

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics