12/02/2013

Java Double-check locking idiom for lazy initialization of fields

注意 : Java 1.5 以上版本才可使用 雙檢鎖, 並要搭配 volatile 關鍵字
private static final Object LOCK = new Object();
private static volatile Singleton instance;

public static Singleton getInstance() {

    Singleton result = instance;
    if (result == null) {
        synchronized (LOCK) {
            result = instance;
            if (result == null) {
                instance = result = new Singleton();
            }
        }
    }
    return result;
}
區域變數 result 看起來是不必要的,但在某些版本的JVM,可以提升執行效率

參考
http://en.wikipedia.org/wiki/Double-checked_locking
http://zh.wikipedia.org/wiki/%E5%8F%8C%E9%87%8D%E6%A3%80%E6%9F%A5%E9%94%81%E5%AE%9A%E6%A8%A1%E5%BC%8F
https://github.com/resteasy/Resteasy/blob/master/jaxrs/jaxrs-api/src/main/java/javax/ws/rs/ext/RuntimeDelegate.java

0 comments:

Post a Comment