Sunday, August 23, 2009

Leaky Abstraction - Double Checked Locking

Some times our inferences based on the abstracted view fails due to the implementation dependencies. This is called leaky abstraction ( http://www.joelonsoftware.com/articles/LeakyAbstractions.html ).
Double Checked Locking idiom was an widely sited design pattern where instead of synchronizing the whole method, synchronize only the initialization part. See the following code snippents
private Helper helper = null;
public synchronized Helper getHelper() {
if (helper == null)
helper = new Helper();
return helper;
}
// other functions and members...
}


Using double checked idiom same code would be implemented as:
private Helper helper = null;
public Helper getHelper() {
if (helper == null)
synchronized(this) {
if (helper == null)
helper = new Helper();
}
return helper;
}
// other functions and members...
}

However it doesn't work. See the following link http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
This is against our (or my) inuition based on the modern language threading model (that execution of method happens in the order of statements written in the code. However that is not correct. Language specifications provide lot of leniency on this part for sake of performance. Compiler optizers typically rewrite the code and final execution not necessarily strict oder as it written in the source code)

1 comment:

Shawn said...

Double-Checked locking is fixed in the memory model of Java5+. You just have to declare your Helper as volatile to prevent the JIT's out-of-order writing optimization.

Bill Pugh also has a better solution to the multi-threaded singleton which doesn't require language specific constructs like synchronized or volatile. He uses a static singletonHolder innerclass: http://en.wikipedia.org/wiki/Singleton_pattern

Cheers