Java Future

I am talking about java.util.concurrent.Future interface which is in Java since 1.5, and absolutely not about the future of Java :). Java Future simply represents the result of an asynchronous computation. When the asynchronous task is created, a Java Future object is returned, this is nothing but a placeholder for the value which will be returned in the future. Once the asynchronous task completes, the result can be accessed via the Future object returned when the task was started.

The Future interface snippet
public interface Future<V> {
    //Attempts to cancel execution of this task 
    boolean cancel(boolean mayInterruptIfRunning) 
    V get(); //waits and returns the result    

    //Waits for most of the given time and returns result if available.
    V get(long timeout, TimeUnit unit);
    boolean isCancelled(); //Returns true if the task has been cancelled.
    boolean isDone(); //Return true if the task is completed.
}
The main implementation of the Future interface is the FutureTask class. It is used by the ExecutorService classes to represent a submitted job.

public class FutureExample {

public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();

Callable<String> callable = () -> {
// Perform some computation
System.out.println("Entered Callable block");
Thread.sleep(2000);
return "Hello from Callable block";
};
System.out.println("Submitting Callable");
Future<String> future = executorService.submit(callable);
// This line executes immediately
System.out.println("Performing some computations");

System.out.println("Retrieve the result of the future");
// Future.get() blocks until the result is available
String result = future.get();
System.out.println(result);
executorService.shutdown();
}
}
The submit method of the executor service submits the task for execution. However it doesn't know when the result of the submitted task will be available. Therefore, it returns a special object of type called Future which can be used to fetch the result of the task when it is available.

Once you called the future.get() method, it will blocks the execution until the result it available. You can use the isDone() method to check whether the task has been completed or not. If you don't want indefinite block of the execution after calling future.get(), you can use the other overloaded get method which takes timeout. This method will throw a TimeoutException, if the task is not completed within the specified time.

Happy Programming...!!!

Comments

Popular posts from this blog

Method Reference in Java Streams

PHP LARAVEL Directory Structure

PHP LARAVEL - Hello World Laravel