This week's giveaway is in the Java/Jakarta EE forum.
We're giving away four copies of Java EE 8 High Performance and have Romain Manni-Bucau on-line!
See welcome thread
Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

When to use ThreadLocal in Java, thread-safety example  RSS feed

Ranch Hand
Posts: 300
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
I can't take it! You are too smart for me! Here is the tiny ad:
ScroogeXHTML 7.2 - RTF to HTML5 / XHTML converter
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!