Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Similarly, threads in a thread pool may fail to be recycled when two executing tasks each require the other to complete before they can terminate. A blocking operation within a subtask can also lead to unbounded queue growth [Goetz 2006].

Noncompliant Code Example (Interdependent Sub-tasks)

...

Private static ThreadLocal variables may be used to maintain local state in each thread. When using thread pools, the lifetime of ThreadLocal variables should be bounded by the corresponding task [Goetz 2006]. Furthermore, programs must not use these variables to communicate between tasks. There are additional constraints in the use of ThreadLocal variables in thread pools; see rule TPS04-J. Ensure ThreadLocal variables are reinitialized when using thread pools for more information.

...

This noncompliant code example contains a series of subtasks that execute in a shared thread pool [Gafter 2006]. The BrowserManager class calls perUser(), which starts tasks that invoke perProfile(). The perProfile() method starts tasks that invoke perTab(), and in turn, perTab starts tasks that invoke doSomething(). BrowserManager then waits for the tasks to finish. The threads are allowed to invoke doSomething() in any order, provided that count correctly records the number of methods executed.

...

This compliant solution selects and schedules tasks for execution, avoiding thread-starvation deadlock. It sets the CallerRunsPolicy on a ThreadPoolExecutor and uses a SynchronousQueue [Gafter 2006]. The policy dictates that when the thread pool runs out of available threads, any subsequent tasks will run in the thread that submitted the tasks.

...

According to Goetz and colleagues [Goetz 2006]

A SynchronousQueue is not really a queue at all, but a mechanism for managing handoffs between threads. In order to put an element on the SynchronousQueue, another thread must already be waiting to accept the handoff. If no thread is waiting, but the current pool size is less than the maximum, ThreadPoolExecutor creates a new thread; otherwise, the task is rejected according to the saturation policy.

According to the Java API [API 2006], the CallerRunsPolicy class is

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

TPS01-J

low

probable

medium

P4

L3

Bibliography

[API 2006]

 

[Gafter 2006]

A Thread Pool Puzzler

[Goetz 2006]

8.3.2, Managing queued tasks; 8.3.3, Saturation Policies; 5.3.3, Dequeues and work stealing

...

      Rule 11: Thread Pools (TPS)Image Added