File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Blog around the Campfire and the fly likes When to use ThreadLocal in Java, thread-safety example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Other » Blog around the Campfire
Bookmark "When to use ThreadLocal in Java, thread-safety example" Watch "When to use ThreadLocal in Java, thread-safety example" New topic
Author

When to use ThreadLocal in Java, thread-safety example

Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 281

ThreadLocal variable is another way of achieving thread-safety in Java. If a class, which is important but not thread-safe and at same time very expensive to create, it make lot of sense to only have limited number of instance of that variable and using ThreadLocal concept to share them between multiple threads. In this article, I have used ThreadLocal variables to provide thread-safety to SimpleDateFormat class. As most of Java programmer knows that SimpleDateFormat is not thread-safe and same time very expensive to create locally, by carefully wrapping them inside ThreadLocal can provide best of both world. By the way be careful, while using ThreadLocal variable in manged environment like J2EE web and application server. Reckless use of ThreadLocal variable can create memory leak in Java web application. For example, storing an object loaded by web app classloader in ThreadLocal, may prevent that class and subsequently that classloader from being Garbage collected, which can create a memory leak in container.


http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use ThreadLocal in Java, thread-safety example
 
Similar Threads
java.text.Format is not thread-safe
I am connecting liferay communtiy edition 6.0.6 with postgresql 9.1 and using apache tomcat server6.
Error in log: ...have started a TimerThread named
Thread local
Using "this" keyword in parent class thread safe?