[concurrency-interest] How seriously should we take broken double checked idiom

Brian Goetz brian at quiotix.com
Mon May 2 23:30:03 EDT 2005


> Double checked idiom is not guaranteed to work in Java. How seriously 
> should we take it? 

Your program is broken.  Is that serious?

> In my current project, there are lot of stateless 
> service classes, which are designed to be singletons. My tech lead says, 
> "We have to use double checked idiom, even if it is not guaranteed to 
> work. It will work most of the times and not many concurrent users are 
> going to access the system".

Oh my god.  Are you serious?

If this is really the totality of his thoughts on the subject, then your 
tech lead really ought to be fired.  This is wrong on more than three 
levels, but I'll restrict myself to the three I'm sure about:

  - Error: lazy initialization is necessary.  This is very often false. 
  While it _may_ be true in your case, his questionable logic in the 
other two points casts considerable doubt on this.

  - Error: double checked locking is the only way to achieve lazy 
initialization.  Dead wrong.  The "Initialization On Demand Holder 
Idiom" (see Jeremy's response, or Effective Java #48.) This idiom beats 
DCL on all fronts -- simplicity, performance, and correctness.

  - Error: It is good enough for a production program to work "most of 
the time" or "as long as there are not too many users."

I might go so far as to say that if your quote is accurate, I would be 
disinclined to believe anything this person says.


Your characterization of the problem is correct -- basically, a thread 
can observe an object to be incompletely constructed, which could cause 
any number of problems -- null pointer exception or similar exception 
being the best possible outcome (because at least then you would find 
out you had a problem.)

As Jeremy points out, DCL instances can be "fixed" by making the 
instance field volatile, _IF_ you are on JDK 5.0 or later.



More information about the Concurrency-interest mailing list