(a)
lock( ... )
if( Z==null )
Z = new Foo();
... = Z;
(b)
// Z must be declared volatile
if( Z==null )
lock( ... )
if( Z==null )
Z = new Foo();
... = Z
Example 3: Double check is an optimization of lazy initialization that avoids acquiring a lock in the common case that Z is already initialized. (a) Lazy initialization; (b) double check.
Back to Article