I have a task which I schedule to run periodically via ScheduledThreadPoolExecutor.scheduleAtFixedRate(task, rate, …). A user can cancel this task manually, which invokes ScheduledFuture.cancel(true). For some reason, perhaps depending on when they cancel this task, the worker thread (which the executor used to run my task) appears to remain in an interrupted status after my task’s run() method exits.
I would have though that worker threads (taken from a pool and reused) would have their interrupted status cleared before starting a new task using the existing hooks (via ThreadPoolExecutor.beforeExecute() or ThreadPoolExecutor.afterExecute()). But it does not do this in the default implementation.
I have two questions:
- How is it that the worker thread is left in a state where the interrupt status is set?
- Why does the default implementation not clear the interrupt status before starting a new task?
The answers are:
From the Oracle library code:
As you can see, the interrupt state is cleared from the worker thread so long as the executor is not shutting down.