Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java cancel Future - How to wait for finish?

Long story short: I have a collection of Future objects. Some of them are already in progress, some are not. I iterate the collection and call future.cancel(false) which, according to the documentation, should cancel all Futures that are not currently running but should allow all the others to complete.

My question is: How do I know when a particular Future is completed after I have called future.cancel(false)? future.isDone() always returns true because cancel() was indeed called before that and future.get() always throws a CancellationException even though the Future is still running.

Any suggestions?

like image 865
mdzh Avatar asked Sep 17 '14 12:09

mdzh


2 Answers

Since Future models the future result of a pending computation, and since that result is not forthcoming from a canceled future, it is reasonable that Future gives you no way to find out when the computation whose result has been disposed of will complete. In other words, you'd need another paradigm to achieve your goal with that approach.

If your wish is to wait for all the submitted tasks to complete, the closest thing which is directly supported by the Executor Service API is to shut down the entire executor service and wait for its termination.

If the above does not fit your solution, then I don't see a better approach than some custom solution, for example a custom implementation of Runnable, which does some housekeeping on the side so you can check when it has completed running.

like image 108
Marko Topolnik Avatar answered Oct 09 '22 08:10

Marko Topolnik


You could add a flag to your Future implementation which will reflect the actual Future' state

like image 1
Katerina A. Avatar answered Oct 09 '22 07:10

Katerina A.