ThreadLocal vs Synchronize & Example
Environment: Java 6
Recently I was looking into capabilities of theThreadLocal. And I decided to test everything against a SimpleDateFormat instance. Unfortunately the SDF is not a thread safe. So in a multi-threaded environment you can avoid concurrent modifications using “Synchronized”. I ran 100000 iterations over small set of 3 dates. Now it was time to implement same thing using ThreadLocal.
public class FormatDate {
private static ThreadLocal<SimpleDateFormat> local =
new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
return sdf;
}
};
public static SimpleDateFormat get() {
return local.get();
}
}
So when I ran my test using ThreadLocal, surprisingly I got benefit of almost ~1000ms over earlier run. This kind of small things matter when it’s part of heavyweight applications. In short using synchronize can be expensive & can be improved by alternate implementations.
Few articles regarding ThreadLocal:
http://www.ibm.com/developerworks/java/library/j-threads3.html
http://javaboutique.internet.com/tutorials/localdata/
http://www.javamex.com/tutorials/synchronization_concurrency_thread_local.shtml