Search code examples
javascheduledexecutorservice

ScheduledExecutorService: How can I wait for cancelled tasks to finish?


I have scheduled some tasks in a ScheduledExecutorService. On shutdown, I'd like to cancel them, and release a database lock once they are all done.

How can I wait for the cancelled tasks to finish processing?

Attempted solutions

  • according to my tests, future.cancel() does not block until the task has stopped executing
  • invoking future.get() after future.cancel() results in an immediate CancelledExecutionException
  • I'd rather not wait for shutdown of the entire executor, as it is shared among components

Solution

  • How can I wait for the cancelled tasks to finish processing?

    The problem with this is that cancellation is done on a best effort basis. The javadoc states

    Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason.

    Typically, cancellation is implemented with interruption and interruption is a convention. Nothing guarantees that it will be implemented correctly. So even if you do send a cancel, nothing guarantees that the underlying task (if already running) will fulfill the cancellation.

    There's no reliable way to implement your use case.