public interface Callable {
V call() throws Exception;
}
Difference between Callable and Runnable Interface
Upasana | July 25, 2020 | 2 min read | 573 views | Multithreading and Concurrency
Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
In order to convert Runnable
to Callable
use the following utility method provided by Executors class
Callable callable = Executors.callable(Runnable task);
Callable, however must be executed using a ExecutorService
instead of Thread as shown below.
Callable<String> aCallable = () -> "dummy";
ExecutorService executorService = Executors.newSingleThreadExecutor();
final Future<String> future = executorService.submit(aCallable);
final String result = future.get();
Submitting a callable to ExecutorService
returns Future Object which represents the lifecycle of a task and provides methods to check if the task has been completed or cancelled, retrieve the results and cancel the task.
Here is the source for Future Interface
public interface Future {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
Summary of differences between Runnable and Callable
-
A Runnable does not return a result
-
A Runnable can’t throw checked Exception, while callable can.
-
Runnable cannot be parametrized while Callable is a parametrized type whose type parameter indicates the return type of its run method
-
Runnable has run() method while Callable has call() method
-
Runnable introduced in Java 1.0 while callable was added in Java 5
Top articles in this category:
- Difference between Implementing Runnable and Extending Thread
- What is difference between HashMap and HashSet
- What is difference between Vector and ArrayList, which one shall be preferred
- Difference between HashMap, LinkedHashMap and TreeMap
- Difference between ExecutorService submit and execute method
- Comparable vs Comparator in Java
- Difference between HashMap and ConcurrentHashMap