Reputation: 70584
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
future.cancel()
does not block until the task has stopped executingfuture.get()
after future.cancel()
results in an immediate CancelledExecutionExceptionUpvotes: 2
Views: 1485
Reputation: 280179
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.
Upvotes: 1