FutureTask in Java

By Arvind Rai, November 16, 2023
1. java.util.concurrent.FutureTask is introduced in Java 5 and is the part of executor framework.
2. FutureTask allows canceling the task by its cancel() method.
3. FutureTask implements the Future interface and its object is created by passing the object of the class which implements Callable.
4. If before calling the run method of FutureTask, task is cancelled, then on calling run method, it will not allow running the thread.

Example-1

FutureTaskTest.java
package com.concretepage;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class FutureTaskTest {
	public static void main(String... args){
		FutureTask<String> ft= new FutureTask<String>(new DemoTask());
		boolean b=ft.cancel(true);
		ft.run();
		System.out.println(b);
	}
}
class DemoTask implements Callable<String>{
	public String call() {
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			System.out.println(e);
		}
		return "Task Done";
	}
} 
In the example we have a thread named as DemoThread which implements Callable interface. Now we have created an object of FutureTask. We call the cancel method. And then call the run method. We can see that now the thread will not run.

Example-2

Find another example that completes its task and uses different method of FutureTask to check the task health.
FutureTaskDemo.java
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.FutureTask;

public class FutureTaskDemo {
	public static void main(String... args) throws InterruptedException, ExecutionException {
		ExecutorService exService = Executors.newSingleThreadExecutor();
		FutureTask<String> futureTask= new FutureTask<String>(new Task());
		exService.execute(futureTask);
		//checks if task done
		System.out.println(futureTask.isDone());
		//checks if task canceled
		System.out.println(futureTask.isCancelled());
		//fetches result and waits if not ready
		System.out.println(futureTask.get());
	}
}
class Task implements Callable<String>{
	public String call() {
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			System.out.println(e);
		}
		return "Task Done";
	}
} 
Find the Output.
false
false
Task Done 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE












©2024 concretepage.com | Privacy Policy | Contact Us