Sunday, October 21, 2007

Lazy Initailization Idioms

Double check idiom is supposedly the best lazy initialization technique

private static Foo foo = null;

public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}

This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.

Solution 1:

private static Foo foo = new Foo();

public static void getFoo(){
return foo;
}

Solution 2:

private static Foo foo = null;

public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}

Solution 3:

Initialize on demand - holder class Idiom

private static class Holder{
static Foo foo = new Foo();
}

public static Foo getFoo(){
return Holder.foo;
}

No comments: