why is static inner class singleton thread safe?

http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

 

public class Singleton {

    // Private constructor prevents instantiation from other classes
    private Singleton() {
        System.out.println("constructor");
    }

    /**
     * SingletonHolder is loaded on the first execution of
     * Singleton.getInstance() or the first access to SingletonHolder.INSTANCE,
     * not before.
     */
    private static class SingletonHolder {
        public static final Singleton INSTANCE = new Singleton();
    }

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

    public static void main(String[] args) {
        System.out.println("main");
        getInstance();
    }

}

 

When to use it

Use this pattern if the initialization of the class is expensive and it cannot be done safely at class-loading time and the initialization is highly concurrent. The crux of the pattern is the safe removal of the synchronization overhead associated with accessing a singleton instance.

其中有一种使用该模式的情况就是在class-loading阶段如果初始化不安全

Since the class initialization phase is guaranteed by the JLS to be serial, i.e., non-concurrent, no further synchronization is required in the static getInstance method during loading and initialization.
类初始化阶段是连续的,也就是非并发的

 

不过构造时也会引起double-checked locking问题 就是会存在某一个瞬间引用不为空但构造未完成。

 

from: http://topic.csdn.net/u/20110222/13/87f22039-9ef0-48d0-8270-c91516e5cee5.html

你可能感兴趣的:(thread,html,.net,Access)