Programs may submit only tasks that support interruption using
Thread.interrupt() to thread pools that require the ability to shut down the thread pool or to cancel individual tasks within the pool. Programs must not submit tasks that lack interruption support to such thread pools. According to the Java API [API 2014], the
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.
Noncompliant Code Example (Shutting Down Thread Pools)
This noncompliant code example submits the
SocketReader class as a task to the thread pool declared in
shutdownNow() method may fail to shut down the thread pool because the task lacks support for interruption using the
Thread.interrupt() method and because the
shutdown() method must wait until all executing tasks have finished.
Similarly, tasks that use some mechanism other than
Thread.interrupted() to determine when to shut down will be unresponsive to
shutdownNow(). For instance, tasks that check a volatile flag to determine whether it is safe to shutdown are unresponsive to these methods. THI05-J. Do not use Thread.stop() to terminate threads provides more information on using a flag to terminate threads.
Compliant Solution (Submit Interruptible Tasks)
This compliant solution defines an interruptible version of the
SocketReader class, which is instantiated and submitted to the thread pool:
TPS02-J-EX0: Short-running tasks that execute without blocking are exempt from this rule.
Submitting tasks that are uninterruptible may prevent a thread pool from shutting down and consequently may cause DoS.