Monday, April 18, 2022

Difference Between Callable and Runnable Interface in Java

Runnable Callable
 It belongs to Java.lang Package It belongs to java.util.concurrent Package
Runnable is introduced in JDK 1.0 Callable is introduced in JDK 5.0
Runnable interface has run() method.
The return type of the run() method is void.
Callable interface has call() method.
 The return type of the call() method is an Future     object.
run() method can't throw checked exception.  call() method can throw checked exception
Runnable use execute() method to put the         task  in queue. Callable use submit() method to put the task in     queue.
We can create thread by passing runnable as a     parameter.  We can’t create thread by passing callable as   
parameter.  Because there is no constructor
 defined in the Thread class which accepts a
 Callable interface. So to execute a Callable         instance,
 you have to use the ExecutorService interface
 of the Java 5 Executor framework. Using             submit() method.

Single Abstract Method : Both have a single abstract method run() method in Runnable and call() method in Callable interface. That means both are functional interfaces and can be used in Lambda expressions since Java8.

new Thread( () -> System.out.println("Runnable") ).start()

Both can be used with the Executors framework. Executors framework defines ExecutorService interface which can accept and execute Runnable and Callable using submit() method.

We can convert Runnable to Callable by using utility method provided by Executors class.

Callable callable = Executors.callable(Runnable task);

Note that Future.get() is a blocking method. Its blocks until execution is finished, so we should use this method with a timeout to avoid deadlock or livelock in our application.

Related Tutorial

No comments:

Post a Comment