[concurrency-interest] Double Checked Locking in OpenJDK

Gregg Wonderly gregg at cytetech.com
Sun Aug 12 15:53:03 EDT 2012

On 8/12/2012 2:35 PM, Richard Warburton wrote:
> Hello,
> The current implementation of java.io.File::toPath [0] appears to be
> using the double checked locking pattern:
>       public Path toPath() {
>           Path result = filePath;
>           if (result == null) {
>               synchronized (this) {
>                   result = filePath;
>                   if (result == null) {
>                       result = FileSystems.getDefault().getPath(path);
>                       filePath = result;
>                   }
>               }
>           }
>           return result;
>       }
> I was going to report the bug, but I'm a little uncertain of the
> interaction between the local variable 'result' and DCL since I've
> previously only seen the checking condition on the shared field
> itself.  Can someone here either confirm that its a bug or explain how
> the 'result' variable is fixing things?

Since filePath is volatile, the double check will "work" from a visibility 
perspective.  The volatile read of filePath goes into the result variable, and 
if it is not set, then the synchronized section creates the necessary 
ordering/control sequence to set filePath correctly.

So, it's the "volatile" on filePath that allows this to work.  Without volatile 
working correctly (the JMM spec changes in JDK 1.5 is where this started working 
on all JVMs), the double check doesn't do the right thing.  Now, this works, and 
has become a quite common "performance" change to reduce locking on lazy 
initializations like this.

Gregg Wonderly

More information about the Concurrency-interest mailing list