user695907
user695907

Reputation: 61

how can i know how a task finished when using java's Future class

I'm using the java's Future class to execute a task, but the method isDone returns true if the task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.

is there a way to know if it ended because an exception or because it finished successfully ?

Upvotes: 5

Views: 1526

Answers (3)

Karthik Jayakumar
Karthik Jayakumar

Reputation: 1

I have used it in my code and the only way you can figure out if the task really completed successfully is by using get()

Upvotes: 0

Eugene Kuleshov
Eugene Kuleshov

Reputation: 31795

When you call Future.get() method, there is 4 possible outcomes:

  • You get the result value
  • You get CancellationException - if the computation was cancelled (e.g. Future.cancel(true) is called)
  • You get ExecutionException - if the computation threw an exception
  • You get InterruptedException - if the current thread was interrupted while waiting (e.g. executor.shutdownNow() is called)

Upvotes: 6

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

You could simply try to retrieve the value - the get method then either throws an exception, or returns the value.

Upvotes: 2

Related Questions