Double-checked locking and the Singleton pattern--双重检查加锁失效原因剖析

以下内容摘取自http://stackoverflow.com/questions/11195389/out-of-order-writes-for-double-checked-locking


Thread1 could publish the instance reference to the main memory, but fail to publish any other data inside the Singleton object that wascreated. Thread2 will observe the object in an inconsistent state.

大概意思是Thread2有可能在Thread1构造函数执行一部分的时候读取Instance,比如Vector赋值,但inUser为false时,这时候就会造成两个线程获取的instance状态不一致。

import java.util.Vector;

class Singleton {

    private static Singleton instance;
    private Vector v;
    private boolean inUse;

    private Singleton() {
        v = new Vector();
        v.addElement(new Object());
        inUse = true;
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) { // 1
                if (instance == null) // 2
                    instance = new Singleton(); // 3
            }
        }
        return instance;
    }
}

 

posted on 2015-08-24 10:52  bendantuohai  阅读(172)  评论(0编辑  收藏  举报