Thursday, May 29, 2008

What's the Role of the Future interface in Java?

Future interface

public interface Future - this interface was added in Java 1.5 and it holds the result of an asynchronous computation. This interface contains methos to check if the asynchronous computataion is complete or still in progress, to wait for the completion of the computation and to block the call until the completion of the computation, and apparently to retrieve the result of the computation.

You can use Future in that case also where you simply want to either check if a task is complete or not or to simply cancel an ongoing task, but you don't want to return any significant result. Use Future to declare the type and return 'null' as the result in such a case.

Methods of the Future interface:-

  • boolean cancel(boolean mayInterruptIfRunning) - this method cancels the task if it's still under progress and returns 'true' in case it successfully cancels it. 'false' is returned if the task has alraedy completed or if the attempt of this method to cancel the task fails due to some other reasons. If the task has not started when the cancel method is called the the task should never run. The parameter mayInterruptIfRunning is used to determine if the thread executing this task should be interrupted or not. If it's true then the thread is interrupted otherwise the taks in progress are allowed to complete and the attempt to cancel the task fails.
  • boolean isCancelled() - it returns 'true' if the task got cancelled before its completion
  • boolean isDone() - it returns 'true' in case the task got completed either due to normal completion or due to exception or due to cancellation of the task using the cancel() method.
  • V get() - if the task has completed, it returns the result, otherwise waits for thr task to get completed first and then returns the result. This method may throw three exception:- One, CancellationException - in case the task was cancelled using cancel() method; Two, ExecutionException - if an exception occured during the execution of the task; Three, InterruptedException - if the thread executing the task was interrupted while it was in the waiting state.
  • V get(long timeout, TimeUnit timeUnit) - As the parameters suggest this variant of get will wait for the specified time only and if the task gets completed before the expiry of the timeout then it returns the result if the computation otherwise returns TimeoutException. It may throw the other three exceptions as well similar to the other variant of get() method.


No comments: