Callable and Future

This Article is part of Series of Articles on Java 8 Concurrency Tutorial.
In this quick article, we’ll focus on a the concept of Callable & Future in the Java language.

Callable

The Callable interface represents a thread that can return the value. It’s the same as the Runnable interface but can return the value.
The callable interface can be used to Compute the value and return it to invoking thread.

Future

Futureis generic interface that represents value which will be returned by callable interface.
There are two methods to get actual value from Future.
get() : When this method is called, thread will wait for result indefinitely.
V get(long timeout, TimeUnit unit) : When this method is called, thread will wait for result only for specified time.

Callable Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class CallableWorkerExample implements Callable<String>
{
private String someReturnValue;
public CallableWorkerExample(String someValue) {
this.someReturnValue=someValue;
}
@Override
public String call() throws Exception {

System.out.println("Working on call");
Thread.sleep(3000);
return this.someReturnValue;
}
}
public class CallableAndFuture {

public static void main(String[] args) throws InterruptedException, ExecutionException {
CallableWorkerExample worker= new CallableWorkerExample("Some Value");
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
Future<String> submit = newSingleThreadExecutor.submit(worker);
System.out.println("Task Submited");
String returnValue = submit.get();
System.out.println("Return value from Callable " +returnValue);
}
}

Key Points

Exception Handling
Runnable.run method does not throws exceptions but Callable.call method throws exception.
ExecutorService
ExecutorService.submit Submits a value-returning task for execution and returns a Future representing the pending results of the task.submitMethod can take Callable and Runnable task as input.But the execute Method Discussed in ExecutorServiceAndThreadPools only takes Runnable task as input.

Share Comments