This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
You can store values in a threadsafe manner. Each thread will have its own threadlocal. For example you can store the Hibernate Session in a threadlocal and reuse it for the same thread rather than creating a new Session each time.
Often, you need to format dates with a certain format, and it's ofcourse a good idea to create the SimpleDateFormat object once (instead of creating a new SimpleDateFormat for every time that you need to format a date). So you might have something like this:
This is going to fail if multiple threads call formatDate(...) at the same time (you might get strange output or exceptions) because SimpleDateFormat is not thread-safe. To make it thread-safe, you can use ThreadLocal:
By doing this, a new SimpleDateFormat object is created for every thread that calls formatDate(), so it will be thread-safe. [ August 18, 2008: Message edited by: Jesper Young ]