...
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution. There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
Wiki Markup |
---|
Consequently, care must be taken so that only interruptible tasks are submitted to the thread pool. When using worker threads that run untrusted tasks or dynamically loaded extension code, provide a way to interrupt the worker. For instance, a worker thread in a thread pool should generally have the following structure (adopted from \[[Goetz 06|AA. Java References#Goetz 06]\]): |
Code Block | ||
---|---|---|
| ||
public void run() {
Throwable thrown = null;
try {
while (!isInterrupted())
runTask(getTaskFromWorkQueue());
} catch (Throwable e) {
thrown = e;
} finally {
threadExited(this, thrown); // Notify upper layers
}
}
|
The worker thread based architecture that uses interruptible workers permits the caller to cleanly terminate misbehaving sub-tasks. If the sub-tasks die because of runtime exceptions, upper layers can take some suitable action such as replacing the worker thread when resources are constrained.
Noncompliant Code Example (shutting down thread pools)
...