ThreadLocal is your friend
Thursday 22 December 2005 @ 12:48 pm
Filed under:

Some years ago I found out about this class being very usefull in your application. You never used a ThreadLocal? I’ll explain the concept and provide some examples.
So what’s the difference between a thread-local variable and a normal variable? When a thread accesses a thread-local variable it has its own independently initialized copy of the variable. Each thread holds an implicit reference to its copy as long as the thread is alive. So when the thread goes away, all of its thread-local instances are subject to gc.
You typically use an anonymous inner class to provide an initial value (if any) using an appropriate constructor and return the newly constructed object.

You can use this ThreadLocal in several situations:

To keep state with a thread (user-id, transaction-id, logging-id)
Log4j uses this for the NDC (Nested Diagnostic Contexts) feature, you surely need this if you ever want to be able to debug a heavily used production application (some more info here).
My current project uses ThreadLocals to trace incoming and outgoing messages (XML via JMS). When we receive a message we put a pseudorandom 44-bit number into the thread-local variable. Important events (exceptions, any outgoing messages, result of processing) are logged with the value of the thread-local variable. This way we correlate events in the main log of the application.

To cache objects which you need frequently
Another way of using a ThreadLocal is for performance optimalization. You can imagine that there are certain objects which are relatively expensive to initialize, but are not threadsafe. Examples of these objects are XML DocumentBuilders (with XSD validation), and SimpleDateFormat (needs a Calendar instance).
When you put the SimpleDateFormat in a thread-local variable, you don’t have to create a local one for every format operation you need to do (we need them quite often), but still are safe with concurrent processing. Implement this as:

public class DateUtil {
   private static final ThreadLocal datetimeFormatter = new ThreadLocal() {
      protected Object initialValue() {
         return new SimpleDateFormat("yyyyMMdd HHmm");
      }
   };
   public static String toDateTime(Date d) {
      SimpleDateFormat sdf = (SimpleDateFormat) datetimeFormatter.get();
      return sdf.format(d);
   }
}

Watch out
Be careful, do not use thread-local variables as instance variables. Although it is not explicitly stated as such in the SDK API docs, they will cause problems when you don’t use them as static variables. Note that this is still an issue in 1.5.

For you J2EE-addicted, these objects can also be held as instance variable in a SLSB (because they’re accessed by one thread at a time), but I tell you, there are still situations you don’t want to create a Enterprise Bean ;-)

— By Klaas van der Ploeg   Comments (4)   PermaLink

Menu


Sha256 mining

Blog Categories

Browse by Date
December 2005
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031 

Upcoming Events

Monthly Archives

Recent Comments

Links


XML Feeds Option


Get Firefox  Powered by WordPress

code validations
Valid RSS 2.0  Valid Atom 0.3
Valid W3C XHTML 1.0  Valid W3C CSS