Difference Between Runnable And Callable in Java

Java programming language provides two ways to implement a class whose instances are to be executed by a thread.

  • By implementing Runnable interface
  • By implementing Callable interface

Since there are two options so they must have some difference in the features they offer, that’s what we’ll discuss in this post; differences between Runnable and Callable in Java.

Runnable Vs Callable in Java

1- Part of Java programming language

Runnable interface is there since Java 1.0.
Callable interface is added in Java 1.5

2- Interface method

Runnable interface has a single method run() with the method signature as following.

Callable interface has a single method call() with the method signature as following.

3- Return value

This is one of major difference between Runnable and Callable in Java. Runnable doesn’t return a result. You can see from the method signature of the run method that the return type is void.

Callable can return a result. Return type of the result is provided at the time of creating Callable instance.

For Example a Callable that returns String.

4- Exception handling

Since Runnable’s run method doesn’t include a throws clause so it is not possible for a Runnable to throw a checked exception.

Following implementation of Runnable results in compile time error “Exception IOException is not compatible with throws clause in Runnable.run()” as IOException is a checked exception.

But it is ok if RunTimeException is thrown.

Callable’s call method does include a throws clause- V call() throws Exception;
so it is possible for a Callable to throw a checked exception.

5- How to execute.

To execute a Runnable task you can use one of the following options-

  1. Thread class has a constructor where you can pass a Runnable as a parameter.
  2. You can use execute method of the Executor interface to run a Runnable task.
  3. You can use submit method of the ExecutorService interface to run a Runnable task.

To execute a Callable task there is no support provided by the Thread class but the concurrent API provides the following options-

  1. You can use submit method of the ExecutorService interface to run a Callable task.
  2. ExecutorService also has invokeAll() and invokeAny() methods where Callable is passed as a parameter.
  3. You can also convert a Runnable object to Callable object by using Executors.callable(Runnable task) provided by utility class Executors.

That’s all for the topic Difference Between Runnable And Callable in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.