Why unsafe Double-Checked-Locking can return null?

时间:2019-01-07 13:05:48

标签: java concurrency thread-safety

I was told unsafe double-checked-locking is bad, for it may returns null on some race conditions, so it should be avoided.

Unsafe Double-Checked Locking idiom:

public class UnsafeDCLFactory {
    private Singleton instance;

    public Singleton get() {
        if (instance == null) {  // read 1, check 1
            synchronized (this) {
                if (instance == null) { // read 2, check 2
                    instance = new Singleton();
                }
            }
        }
        return instance; // read 3
    }

    static class Singleton {
        private Date d;
        public Singleton() {
            this.d = new Date();
        }
    }
}

when we call get() method, null may be returned though it's very very rare. But i just wonder why null can be returned? Does it mean even if 'read 1' read a non-null value, 'read3' can still read a null one?

1 个答案:

答案 0 :(得分:0)

Yes, it is possible (although very, very unlikely).

Have a look at this article about safe publication in Java. It also handles the double-checked locking and the possible "null" return.