Wiki Markup |
---|
The {{java.lang.ThreadLocal<T>}} class provides thread-local variables. According to the Java API \[[API 2006|AA. JavaBibliography#API References#API 06]\] |
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 typicallyprivate static
fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
Wiki Markup |
---|
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 when thread creation overhead is too expensive or when creating an unbounded number of threads can diminish the reliability of the system. Every thread that enters the pool expects to see an object in its initial, default state. However, when {{ThreadLocal}} objects are modified from a thread that is subsequently made available for reuse, the reused thread sees the state of the {{ThreadLocal}} object as set by the previous thread \[[JPL 2006|AA. JavaBibliography#JPL References#JPL 06]\]. |
Noncompliant Code Example
...
Wiki Markup |
---|
If the thread-local variable is read by the same thread again, it is reinitialized using the {{initialValue()}} method, unless the thread has already set the variable's value explicitly \[[API 2006|AA. Java References#APIBibliography#API 06]\]. This solution transfers the responsibility for maintenance to the client ({{DiaryPool}}) but is a good option when the {{Diary}} class cannot be modified. |
...
Wiki Markup |
---|
\[[API 2006|AA. Java References#APIBibliography#API 06]\] class {{java.lang.ThreadLocal<T>}} \[[JPL 2006|AA. Java References#JPLBibliography#JPL 06]\] 14.13. ThreadLocal Variables |
...