Mega Code Archive

 
Categories / Java Book / 007 Thread Conncurrent
 

0402 Using Callable and Future

Callable interface represents a thread that returns a value. You can use Callable objects to do calculation. Callable is a generic interface: interface Callable<V> V indicates the type of data returned by the task. Callable defines only one method, call( ): V call( ) throws Exception You define the task that you want performed in call( ) method. After that task completes, you return the result. If the result cannot be computed, call( ) must throw an exception. A Callable task is executed by submit( ) method from ExecutorService. It is shown here: <T> Future<T> submit(Callable<T> task) task is the Callable object that will be executed in its own thread. The result is returned through an object of type Future. Future is a generic interface that represents the value returned by a Callable object. Future is defined like this: interface Future<V> V specifies the type of the result. To obtain the returned value, you will call Future's get( ) method, which has these two forms: V get( ) throws InterruptedException, ExecutionException waits for the result indefinitely. V get(long wait, TimeUnit tu) throws InterruptedException, ExecutionException, TimeoutException specify a timeout period to wait. import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main { public static void main(String args[]) { ExecutorService es = Executors.newFixedThreadPool(3); Future<Integer> f = es.submit(new Sum()); try { System.out.println(f.get()); } catch (Exception exc) { System.out.println(exc); } es.shutdown(); } } class Sum implements Callable<Integer> { Sum() { } public Integer call() { int sum = 0; for (int i = 1; i <= 100; i++) { sum += i; } return sum; } }