Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 704
user695907 Avatar asked Jul 12 '11 16:07

user695907


People also ask

What is a Future How is it used in ExecutorService?

When one submit a task to ExecutorService which is take a long running time, then it returns a Future object immediately. This Future object can be used for task completion and getting result of computation.

What is Future task?

A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable , a FutureTask can be submitted to an Executor for execution. In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.

What is the Future class in Java?

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.


1 Answers

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)
like image 119
Eugene Kuleshov Avatar answered Oct 06 '22 00:10

Eugene Kuleshov