Future Interface

This lesson discusses the Future interface.

We'll cover the following...

Future Interface

The Future interface is used to represent the result of an asynchronous computation. The interface also provides methods to check the status of a submitted task and also allows the task to be cancelled if possible. Without further ado, let's dive into an example and see how callable and future objects work in tandem. We'll continue with our sumTask example from the previous lesson.

Press + to interact
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;
class Demonstration {
// Create and initialize a threadpool
static ExecutorService threadPool = Executors.newFixedThreadPool(2);
public static void main( String args[] ) throws Exception {
System.out.println( "sum :" + findSum(10));
threadPool.shutdown();
}
static int findSum(final int n) throws ExecutionException, InterruptedException {
Callable<Integer> sumTask = new Callable<Integer>() {
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= n; i++)
sum += i;
return sum;
}
};
Future<Integer> f = threadPool.submit(sumTask);
return f.get();
}
}

Thread pools implementing the ...