Menu Home

Java:线程安全的单例

public class Singleton {

    private static class SingletonHolder {
        private static Singleton sSingleton = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.sSingleton;
    }

    private Singleton() {

    }
}

基于以下事实:

  • JVM加载class是线程安全的。
  • class的static成员在类首次加载时初始化。

Categories: java

Tagged as:

lnmcc

Leave a Reply

Your email address will not be published.