by BehindJava

The difference between the Runnable and Callable interfaces in Java

Home » java » The difference between the Runnable and Callable interfaces in Java

In this tutorial we are going to learn about the differences between Runnable and Callable interfaces in Java.

Let us look at where one would use Runnable and Callable.

Runnable and Callable both run on a different thread than the calling thread. But Callable can return a value and Runnable cannot. So where does this really apply.

Runnable : If you have a fire and forget task then use Runnable. Put your code inside a Runnable and when the run() method is called, you can perform your task. The calling thread really does not care when you perform your task.

Callable : If you are trying to retrieve a value from a task, then use Callable. Now callable on its own will not do the job. You will need a Future that you wrap around your Callable and get your values on future.get (). Here the calling thread will be blocked till the Future comes back with results which in turn is waiting for Callable’s call() method to execute.

So think about an interface to a target class where you have both Runnable and Callable wrapped methods defined. The calling class will randomly call your interface methods not knowing which is Runnable and which is Callable.

The Runnable methods will execute asynchronously, till a Callable method is called. Here the calling class’s thread will block since you are retrieving values from your target class.

NOTE :

  • Inside your target class you can make the calls to Callable and Runnable on a single thread executor, making this mechanism similar to a serial dispatch queue.
  • So as long as the caller calls your Runnable wrapped methods the calling thread will execute really fast without blocking. As soon as it calls a Callable wrapped in Future method it will have to block till all the other queued items are executed.
  • Only then the method will return with values. This is a synchronization mechanism.