Using Thread Local Variables

The ThreadLocal and InheritableThreadLocal are two classes that most Java developers might not use properly or even know exist. These classes provide a mechanism to set up an object that can be associated with a specific thread and have the thread access its copy of the object. In other words, it's a way to associate a state with a thread. The ThreadLocal class can hold onto objects only, not primitives.

You might be asking, how is this different than declaring a private variable within a thread class. That's an important question. Normally, a ThreadLocal object is declared as a private static variable in some class. You'll remember that this means all instances of this class have access to it. Every time a new thread ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.