Callable and Runnable in Java

What is difference between Callable and Runnable in Java, is very important and frequntly asked question in interview these days if interviewer wants to know your understanding on java threading.

Runnable and Callable ,both are interfaces in java which provides way to create thread in java .Runnable Interface was part of JDK since JDK 1.0. By implementing Runnable interface and providing functionality into it’s run() method, we can define a task which a thread need to do.

Runnable provide a way to create task for parallel executing in multi threaded environment. Runnable cannot return the result of computation which is essential if you are performing some computing task in another thread and Runnable cannot throw checked exception.

Due to limitation of Runnable,  Callable came to Java 5 to overcome limitation of Runnable .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 cancelled, retrieve the result or cancel the task. Since return type of Runnable’s run() method is void, it cannot return anything.

Callable’s call() method can throw Checked exception while Runnable’s run() method cannot throw any checked exception.

Method signature that has to overridden for implementing Callable.

public Object call() throws Exception;

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.

You can not pass Callable  in to Thread as you pass the Runnable instance in Thread constructor . 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.

Note :  Future.get() is a blocking method and blocks until execution is finished, so you should always call this method with a timeout to avoid deadlock or livelock in your application.

Future is returning type form ExecutorService.submit(new MyCallable()) method. This is interface having method like isDone(), get(), cancel(), isCancelled() to check the status and get result from Callable thread/task.

I would suggest Java lover and Java Professional to read “Java Concurrency In Practice” to have deep understanding on java multi-threading .

Also very nice article on java.util.concurrrent package which was added in Java 5   by @JJenkov.

You may also like

Leave a Reply

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