`
wxyfighting
  • 浏览: 191186 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

精妙的单例类(Singleton)

 
阅读更多

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

Java代码收藏代码
  1. publicclassSingleton{
  2. //aninnerclassholdertheuniqueInstance.
  3. privatestaticclassSingletonHolder{
  4. staticfinalSingletonuniqueInstance=newSingleton();
  5. }
  6. privateSingleton(){
  7. //Existsonlytodefeatinstantiation.
  8. }
  9. publicstaticSingletongetInstance(){
  10. returnSingletonHolder.uniqueInstance;
  11. }
  12. //Othermethods...
  13. }

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.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics