欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

精妙的单例类(Singleton)

程序员文章站 2022-03-07 18:06:42
...

《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

 

相关标签: Singleton