What is double-checked locking? Does it work?

Alex Chaffee

Double-checked locking (DCL) is an idiom recommended by a number of Java books and articles as a way to reduce synchronization overhead when performing lazy initialization.

The DCL idiom was designed to support lazy initialization, which occurs when a class defers initialization of an owned object until it is actually needed.

Unfortunately, DCL isn't guaranteed to work under the current Java Memory Model (JMM).

See the following articles by Brian Goetz (from which this FAQ answer is excerpted):

Briefly, the following single-checked code is thread-safe:


class SomeClass {
  private Resource resource = null;

  public synchronized Resource getResource() {
    if (resource == null)
      resource = new Resource();
    return resource;
  }
}
but the following double-checked code is faster, but thread-unsafe:

class SomeClass {
  private Resource resource = null;

  public Resource getResource() {
    if (resource == null) {
      synchronized {
        if (resource == null) 
          resource = new Resource();
      }
    }
    return resource;
  }
}
In my (Alex's) humble opinion, the whole debate is misguided and somewhat moot: you should just trust the JVM to make synchronized as fast as possible, and most of the time it will work out OK. Furthermore, if the bottleneck in your code is instance variable initialization, then it's probably *not* instance variable access (and vice versa), so pick one (lazy initialization or constructor-time initialization) and cross your fingers :-)
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact