I'm tracking execution of a task with standard Future
object. There are the following valid states of that task (as I see in Guava code of AbstractFuture
class):
Future.isDone()
returns true
if and only if the state is completed, cancelled or interrupted. Future.isCancelled()
returns true
if and only if the state is either interrupted or cancelled.
Ok, but I need to check if the task is completed. There is an obvious way to do this:
boolean isCompleted = future.isDone() && !future.isCancelled();
Unfortunatelly, a nasty concurrency bug hides there.
future.isCancelled()
. The result is false
, because the task is still in progress.future.cancel()
.future.isDone()
. The result is true
now.true
, and it's incorrect answer.How to avoid this issue?
You can try calling get(..)
with an extremely short timeout. If it returns a value, it was completed. If you get a TimeoutException
, it wasn't. If you get any other of the possible exceptions, it was either cancelled, failed, or was interrupted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With