Difference between Runnable vs Callable interface

1) Existence and Availability

First and most important difference between Runnable and Callable interface is that Runnable is available in Java right from the beginning i.e. JDK 1.0 while Callable was later added to Java 5, so you cannot use Callable before Java 5.


2) Result
The second key difference between Callable and Runnable is that Callable can return the result of parallel processing of a task. It returns a Future object, which represents the lifecycle of a task and provides methods to check if the task has been completed or canceled, retrieve the result or cancel the task. Since return type of Runnable'run() method is void, it cannot return anything.


3) Checked Exception
Another worth noting difference between these two interfaces is that Callable's call() method can throw Checked exception while Runnable's run() method cannot throw checked exception.


4) The call() vs run() methods
In order to use Callable, you need to override the call() method while in order to use Runnable interface you need to override the run() method in Java.


5) Execution
There is one limitation while using Callable interface in Java that you cannot pass it to Thread as you pass the Runnable instance. There is no constructor defined in the Thread class which accepts a Callable interface. So in order to execute a Callable instance you need to use the ExecutorService interface of Java 5 Executor framework. This interface defines submit() method which accepts a Callable instance and return a Future object which holds the result of computation as shown below:

Read more: https://javarevisited.blogspot.com/2016/08/useful-difference-between-callable-and-Runnable-in-Java.html#ixzz5eyBM1hiv

Comments

Popular posts from this blog

Can we Overload or Override static methods in java ?

Difference between Comparable and Comparator

Differences Between Enumeration And Iterator In Java