#
FutureTask class in Java
Future
interface is used to represent the future result of an asynchronous computation.
The interface provides the methods to check if the computation is completed or not,
to wait for its completion, and to retrieve the result of the computation.
The FutureTask class is an implementation of Future & Runnable, and therefore can be run by an Executor.
This implementation is not very used, but it is an alternative to using directly the Future interface with a Callable interface.
The usage is not very complicated. Take a look at the following example:
package com.exampe.java;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.concurrent.*;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
SpringApplication.run(DemoApplication.class, args);
System.out.println("--------------------------------------------");
FutureTask<Integer> futureTask1 = new FutureTask<Integer>(()-> {
System.out.println("The futureTask1 is working");
Thread.sleep(1000);
return 10;
});
FutureTask<Integer> futureTask2 = new FutureTask<Integer>(()-> {
System.out.println("The futureTask2 is working");
Thread.sleep(500);
return 20;
});
ExecutorService es = Executors.newFixedThreadPool(10);
// Run a task (callable). The task has a result kept in the future object
es.execute(futureTask1);
es.execute(futureTask2);
System.out.println("--------------------------------------------");
while (true) {
try {
if(futureTask1.isDone() && futureTask2.isDone()){
Integer mySum = futureTask1.get()+futureTask2.get();
System.out.println("SUM = "+mySum);
System.out.println("Done");
//shut down executor service
es.shutdown();
return;
}
if(!futureTask1.isDone()){
//wait indefinitely for future task to complete
System.out.println("FutureTask1 output="+futureTask1.get());
}
System.out.println("Waiting for FutureTask2 to complete");
Integer res2 = futureTask2.get(200L, TimeUnit.MILLISECONDS);
if(res2 !=null){
System.out.println("FutureTask2 output="+res2);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}catch(TimeoutException e){
//do nothing
}
}
}
}
When I run it, I got the following result:
--------------------------------------------
--------------------------------------------
The futureTask1 is working
The futureTask2 is working
FutureTask1 output=10
Waiting for FutureTask2 to complete
FutureTask2 output=20
SUM = 30
Done
You can also take a look at the following articles: