The java.lang.ThreadLocal<T>
class provides thread-local variables. According to the Java API [API 2006]:
These variables differ from their normal counterparts in that each thread that accesses one (via its
get
orset
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 (for example, a user ID or transaction ID).
The use of ThreadLocal
objects requires care in classes whose objects are required to be executed by multiple threads in a thread pool. The technique of thread pooling allows threads to be reused to reduce thread creation overhead or when creating an unbounded number of threads can diminish the reliability of the system. Each task that enters the pool expects to see ThreadLocal
objects in their initial, default state. However, when ThreadLocal
objects are modified on a thread that is subsequently made available for reuse, the next task executing on the reused thread sees the state of the ThreadLocal
objects as modified by the previous task that executed on that thread [JPL 2006].
Programs must ensure that each task that executes on a thread from a thread pool sees only correctly initialized instances of ThreadLocal
objects.
...
If the thread-local variable is read by the same thread again, it is reinitialized using the initialValue()
method unless the task has already set the variable's value explicitly [API 2006]. This solution transfers the responsibility for maintenance to the client (DiaryPool
) but is a good option when the Diary
class cannot be modified.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
TPS04-J | medium | probable | high | P4 | L3 |
Bibliography
...
Rule 11: Thread Pools (TPS) Rule 12: Thread-Safety Miscellaneous (TSM)