Monday, March 05, 2007

ThreadLocal – A Wrapper Class for Thread Safe

In his article “Thread-safe webapps using Spring”, Steven Devijver talked about the idea behind the thread-safe template classes through which Spring achieves the Data Access Abstraction.

Basically the template thread-safe is fulfilled by using a wrapper class "ThreadLocal". The following code provides a simple example that shows how the ThreadLocal class work.

private static ThreadLocal pi = new ThreadLocal();

public Double pi() {
if (pi.get() == null) {
pi.set(new Double(22 / 7));
}
return (Double)pi.get();
}

ThreadLocal class wraps any object and binds it to the current thread thus making objects local to the thread. When a thread executes the pi() method for the first time there will be no object bound to the thread by ThreadLocal instance pi so the get() method will return null.The set() method will bind an object to the thread that is not shared by other threads. If the method pi() is called often per thread this approach may still offer a considerable performance gain while guaranteeing thread-safety.