Java Future Example

By Arvind Rai, December 29, 2013
java.util.concurrent.Future has been introduced in JDK 5 and is the part of executor framework. It represents the output of an asynchronous computation. Future has many methods that check the health of running task and gives the information in calling thread. There are methods in Future which checks if computation is complete and if not main thread can wait and gets the result. Future can also give the information that computation has completed normally or has been canceled. Find some method description.

cancel() : It attempts to cancel the task and returns true or false.

get(): Fetches the result and waits if task is not completed.

isDone(): If task is completed . it returns true otherwise false.
package com.concretepage;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class JavaFutureDemo {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService exService = Executors.newSingleThreadExecutor();
		Callable<String> task = new DemoTask();
		Future<String> future = exService.submit(task);
		//checks if cancelled
		System.out.println("Is task cancelled:"+future.isCancelled());
		//checks if task done
		System.out.println("Is task done:"+future.isDone());
		//waits to complete and fetches the value.
		String s = future.get();
class DemoTask implements Callable<String>{
	public String call() {
		try {
		} catch (InterruptedException e) {
		return "Task Done";
In the example we have a callable thread that will return a string value after two second.
Is task cancelled:false
Is task done:false
Task Done

©2023 | Privacy Policy | Contact Us