Future.cancel(true) returns true but tasks not cancelled

Viewed 194

On local machine, I have a runnable task which I am cancelling using future.cancel(true), which returns true and I see ThreadPoolTaskExecutor has no pending tasks.

However on a different environment (which is a container), I see future.cancel(true) return true, but ThreadPoolTaskExecutor does not accept new tasks, because previous tasks are not cancelled.

Any ideas why this can happen? Here is what I'm doing.

Task task = new Task();
Future<String> future = threadPoolTaskExecutor.submit(task);

// wait for some time
boolean val = future.cancel(true)

// still cannot submit more tasks

private class Task implements Callable<String> {
    @Override
    public String call() throws InterruptedException {
        Thread.sleep(10000);
      return "value";
    }
}
1 Answers

The JavaDoc could be clearer, but what cancel actually does is cancelling the future and optionally interrupting its thread. If this succeeds it returns true. However, there is no guarantee that the thread actually does terminate as a result of this. In the case of mayInterruptIfRunning this can happen if the thread does not properly handle InterruptedException in all places.

See e.g. the source code for FutureTask.cancel.

Related