Monday, June 07, 2004

The Double-check Locking Idiom is broken

After reading Raymond Chen's very insightful blog a couple of nights ago, I couldn't resist investigating the Double Check lock idiom on the Internet. There is a whole bunch of literature on the topic but here is a quick introduction. In today's world of multi-processor machines, synchronization has become one of the biggest headaches for systems programmers. There is also the added need to make code run as fast as possible, therefore, reducing the size of critical sections and number of acquisitions of mutexes/locks/semaphores (since acquiring a lock is an expensive operation in terms of time, the cache and the pipeline). Sometime in 1996, Doug Lea came up with this idea for creating a Singleton (refer the GoF book on Design Patterns) but making the code acquire the lock only once and return the instance in the most commonly encountered codepath. Here is a code sample in Java:
class Foo { 

private Helper helper = null;
public Helper getHelper() {
if (helper == null)
synchronized(this) {
if (helper == null)
helper = new Helper();
}
return helper;
}
}

It was later determined that this code breaks in the case where the compiler optimizes instructions within the synchronized block such that a consumer of the helper instance might see non-initialized members in the object.

The "Double-Checked Locking is Broken" Declaration paper provides insight into why the algorithm is broken and a possible way of fixing it. The way to solve this in Windows will be the topic of another blog post. In the interim, feel free to post any solutions that you think will solve the problem.

No comments:

Post a Comment