[concurrency-interest] Understanding volatile in DCL

luo.fucong bayinamine at gmail.com
Tue Aug 4 23:55:09 EDT 2015


It is mentioned in the wiki of double-checked locking idiom(https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java <https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java>) that DCL without introducing “volatile” keyword is broken:

// Broken multithreaded version
// "Double-Checked Locking" idiom
class Foo {
    private Helper helper;

    public Helper getHelper() {
        if (helper == null) {    
            synchronized(this) {    
                if (helper == null) {    
                    helper = new Helper();
                }
            }
        }    
        return helper;
    }

    // other functions and members…
}

It’s broken because a thread may obtain a partially constructed object (the variable “helper” may be initialized before constructor “new Helper()” finished due to reordering).

I am wondering is there another possible of why that is broken that, the “helper” may be initialized more than once?

Say Thread1 and Thread2 are now concurrently trying to get the helper instance, and T1 obtains the monitor(enter the synchronized block) while T2 waits.

Then T1 initialized the helper and returned, T2 entered the synchronized block. However, without the “volatile” keyword, T2 may not see the update of the helper variable that were made by T1. So T2 may think that "helper == null” is true, and thus initialize the helper again.

Is the above possible? Thanks in advance!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20150805/aec98bc8/attachment.html>


More information about the Concurrency-interest mailing list