Callable & Future Interfaces
21 Feb 2017 Java #java #threadsA Callable is a generic interface, represents a thread which will return a value.
It has a single method call() which throws Exception and returns an object of given type.
V call() throws Exception;Callable is similar to Runnable with two major differences.
-
Runnabletask can not return a value while aCallablecan. -
Callablecan throw an exception while aRunnablecan not.
A
Callablemust return a value if task is completed successfully or in case of failure an exception must be thrown.
ExecutorService#submit method accepts objects of type callable and execute them in their own threads.
Future
ExecutorService#submit returns an object of type Future which represents the result of Callable thread.
V get() throws InterruptedException, ExecutionException;Future object can be queried for getting information about task cancellation or completion. The most important method of Future object is get() which returns the result of Callable object.
get() is a blocking a call and it stops the execution of current thread unless one of the following event occurs
-
Current thread is interrupted (
InterruptedExceptionis thrown). -
Task is canceled (
CancellationExceptionis thrown).
or
- Task throws an exception (
ExecutionExceptionis thrown.)
Example
App.java
public class App {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newFixedThreadPool(2);
Future<String> future = es.submit(() -> {
System.out.println("waiting in " + Thread.currentThread().getName());
Thread.sleep(3000);
return "some random result";
});
System.out.println(future.get());
es.shutdown();
} // main
} // AppOutput
waiting in pool-1-thread-1
some random result