...
This noncompliant code example uses the SocketReader
class defined earlier in Compliant Solution (close socket connection) of the guideline CON24-J. Ensure that threads and tasks performing blocking operations can be terminated and submits it as a task to a thread pool defined in class PoolService
.
Code Block | ||
---|---|---|
| ||
public final class PoolService {
private final ExecutorService pool;
public PoolService(int poolSize) {
pool = Executors.newFixedThreadPool(poolSize);
}
public void doSomething() throws InterruptedException, IOException {
pool.submit(new SocketReader());
// ...
List<Runnable> awaitingTasks = pool.shutdownNow();
}
public static void main(String[] args) throws InterruptedException, IOException {
PoolService service = new PoolService(5);
service.doSomething();
}
}
public final class SocketReader implements Runnable {
private final Socket socket;
// ...
}
|
Because the task does not support interruption through the use of Thread.interrupted()
, there is no guarantee that the shutdownNow()
method will shutdown the thread pool. Using the shutdown()
method does not fix the problem either, because it waits until all executing tasks have finished. Likewise, tasks that check a volatile
flag to determine whether it is safe to shutdown are not responsive unresponsive to these methods.
Compliant Solution (submit interruptible tasks)
Tasks that do not support interruption using Thread.interrupt()
should not be submitted to a thread pool. This compliant solution submits the interruptible version of SocketReader
discussed in Compliant Solution (interruptible channel) of the guideline CON24-J. Ensure that threads and tasks performing blocking operations can be terminated, to the thread pool.
Code Block | ||
---|---|---|
| ||
public final class PoolService {
// ...
}
public final class SocketReader implements Runnable {
private final SocketChannel sc;
// ...
}
|
Similarly, when trying attempting to cancel individual tasks within the thread pool using the Future.cancel()
method, ensure that the task supports tasks support interruption. If it doesthey do, pass a boolean
argument true
to cancel()
, otherwise pass false
. The value false
indicates that the a task will be canceled if it has not already started.
...