...
Wiki Markup |
---|
The use of {{ThreadLocal}} objects is insecure in classes whose objects are required to be executed by severalmultiple threads, together in a thread pool. The technique of thread pooling allows threads to be reused when thread creation overhead is too high or creating an unbounded number of threads iscould a potential threat to affect the reliability of the system. Every thread that enters the pool expects to see an an object in its initial, default state. However, when {{ThreadLocal}} objects are setmodified from a thread which is subsequently made available for reuse, the reusingreused thread whichwill takessee itsthe placestate mayof see the most recent state that was {{ThreadLocal}} object as set by the previous thread instead of the expected, default state. \[[JPL 06|AA. Java References#JPL 06]\]. |
Noncompliant Code Example
This noncompliant code example consists of an enumeration Day
of days (Day
) and two classes , (Diary
and DiaryPool
). The class Diary
uses a ThreadLocal
variable to store thread-specific information, such as each thread's current day. The initial value of the current day is Monday, and ; this can be changed later by using invoking the setDay()
method. The class also contains a threadSpecificTask()
instance method that performs a thread-specific task.
The class DiaryPool
consists of two methods doSomething1()
and doSomething2()
that each start one a thread each, respectively. The method doSomething1()
method changes the initial (default) value of the day in the diary to Friday and invokes the threadSpecificTask()
method. On the other hand, the method doSomething2()
relies on the initial value of the day (Monday) in the diary and invokes the threadSpecificTask()
method. The main()
method creates one thread using doSomething1()
and two more using doSomething2()
.
...