dev@glassfish.java.net

Re: a more efficient way to initialize Loggers?

From: Peter Williams <Pete.Williams_at_Sun.COM>
Date: Thu, 07 Dec 2006 13:02:09 -0800

Lloyd L Chambers wrote:
> Peter,
>
> I am familiar with the double-checked lock pattern.
I figured you were, I just missed the volatile on first read and
couldn't remember under what circumstance that usage was guaranteed to
fix the problem.

Anyway, I already replied to the thread with a corrected comment. The
very last paragraph on p 348 of JCiP indicates the requirements for this
to work -- 1. field is volatile, 2. JVM version >= 5.0 (true for
AppServer 9.x -- don't let someone backport this fix to 8.2 though since
it has to run on 1.4).

-Peter
> It is typically written as:
>
> if ( thing != null) {
> synchronized( this ) {
> if ( thing == null ) {
> thing = new Thing();
> }
> }
>
> But that's not what I've written below.
>
> 1. The first check is to see if _logger is NOT null. If it's not
> null, then it exists. It is (crucially) declared as 'volatile', so all
> threads can see its current value.
>
> 2. Synchronized code cannot be moved up above the check for non-null
> in step 1. That's my understanding from "Java Concurrency" at least.
>
> 3. The synchronized block synchronizes *before* it makes the check for
> null.
>
> So why won't the code snippet work?
>
> Lloyd
>