Tech Master Tutorials
Email Facebook Google LinkedIn Pinterest Twitter
Home Java Java 8 Java Interview Questions Java Programming

Future


Go to Creating Threads in Java to know the basics of thread creation in Java.
Go to Java Concurrency Framework to know the Java concurrency classes.


Below we have a simple callable task that is returning an Integer value.

import java.util.concurrent.Callable;

public class ExecutorCallable implements Callable<Integer>{

	@Override
	public Integer call() throws Exception {
		int sum = 0;
		for (int i = 1; i < 10; i++) {
			sum+=i;
		}
		return sum;
	}
	
}


In the below code, we have the main class in which creating an instance of the Callable task and passing it to the executor using submit() method.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MainClass_Callable {

	public static void main(String[] args) {
		ExecutorCallable callableObj = new ExecutorCallable();
		ExecutorService executor = Executors.newSingleThreadScheduledExecutor();
		Future<Integer> intResult = executor.submit(callableObj);

		try {
			if (!intResult.isDone()) {
				Thread.sleep(1000);
			}
			int result = intResult.get();
			System.out.println("result from future = " + result);
			executor.shutdown();
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
}

As part of the above example we have Future class which holds the result returned from the thread.
Future wait for the result to be returned from the thread and then hold it which can be retrieved using get() method.

Future : A Future represents the result of an asynchronous computation.
Future provides below useful methods –
• get() – get is used to get the result of the asynchronous computation. If computation is still in progress thn get() method will block the program in which the get() is called. So get should be used with proper thought otherwise execution may block.
• isDone() – isDone() does not block. Simple returns true if thread is executed and result is available. In program isDone() can be used to check if asynchronous computation is done and then get()call can b made.
• Cancel() – cancellation of the task is done using the cancel method.

Java 8 onwards, CompletionStage interface and CompletableFuture implementation class has been introduced.
CompletionStage allows you to combine multiple threads serially. While excuting in serial, the result of one completion stage can be passed to another completion stage.
CompletionStage also allows to execute multiple threads concurrently and then combine.
CompletionStage/CompletableFuture provides wide variety of methods to manage threads.

As we know that the Callable is a Functional Interface.
So instead of defining a Callable, then instantiating and then passing to the executor through submit,
we can pass a lambda expression for the same.


In the below example, passing lambda expression to the executor instead of callable instance.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MainClass {

	public static void main(String[] args) {
		ExecutorService executor = Executors.newFixedThreadPool(5);
		Future<Integer> intResult = executor.submit(
					() -> {
						int sum = 0;
						for (int i = 0; i < 10; i++) {
							sum +=i;
						}
						return sum;
					}
				);

		try {
			if (!intResult.isDone()) {
				Thread.sleep(1000);
			}
			int result = intResult.get();
			System.out.println("result from future = " + result);
			executor.shutdown();
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
	
}