单例模式多线程安全写法(double-lock-check)

原始版本

public static Object getInstance() {
    if (instance != null) {
        return instance;
    }

    instance = new Object();
    return instance;
}

不足:没有考虑多线程

版本1:

public static synchronized  Object getInstance() {
    if (instance != null) {
        return instance;
    }

    instance = new Object();
    return instance;
}

不足:这样会导致每次调用都是同步,效率低

 

double-lock-check

private static final Object lock = new Object();
private static volatile Object instance; // must be declared volatile

public static Object getInstance() {
    if (instance == null) { // avoid sync penalty if we can
        synchronized (lock) { // declare a private static Object to use for mutex
            if (instance == null) {  // have to do this inside the sync
                instance = new Object();
            }
        }
    }

    return instance;
}

 

posted @ 2017-06-26 15:44  Season2009  阅读(708)  评论(0编辑  收藏  举报