A variable should always be declared in the smallest scope possible but a ThreadLocal
provides a much bigger scope and should be used only for variable that is needed across many lexical scopes. As per doc:
These variables differ from their normal counterparts in that each
thread that accesses one (via its get or set method) has its own,
independently initialized copy of the variable. ThreadLocal instances
are typically private static fields in classes that wish to associate
state with a thread (e.g., a user ID or Transaction ID).
So they are used when you have a common code and you want to save state on a per thread basis. An example is provided in doc:
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread's ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
// Returns the current thread's unique ID, assigning it if necessary
public static int get() {
return threadId.get();
}
}
In the above example, the classThreadId
generates unique identifiers which is local to each thread which is not changed on subsequent calls. Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection.
How does ThreadLocal variable reduces the cost of creating expensive
objects?
Until some benchmark supports this claim I am not sure this is even the case with latest JVMs.