#
Future interface 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 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("--------------------------------------------");
Callable<Integer> callable1 = () -> {
{
System.out.println("Callable #1 is running");
};
return 10;
};
Callable<Integer> callable2 = () -> {
{
System.out.println("Callable #2 is running");
Thread.sleep(3000);
};
return 20;
};
ExecutorService es = Executors.newFixedThreadPool(10);
// Run a task (callable). The task has a result kept in the future object
Future<Integer> f1 = es.submit(callable1);
Future<Integer> f2 = es.submit(callable2);
// block the current thread and get/wait the results of the 2 ASYNC calls
Integer mySum = f1.get()+f2.get();
System.out.println("Futures sum = "+mySum);
// Stop the Executor Service
es.shutdown();
System.out.println("--------------------------------------------");
}
}
You can also take a look at the following articles: