Learnitweb

Difference between Runnable and Callable

Both Runnable and Callable interface are used to encapsulate task supposed to be executed by another thread. Runnable and Callable both run on a different thread than the calling thread. There are certain things which Runnable can not do like throwing checked exception and returning result after computation. Java team could have changed the signature but due to backward compatibility this could not be implemented.

Callable represents a task that can return a result and may throw an exception. Callable has following method:

V call() throws Exception

A Runnable, however, does not return a result and cannot throw a checked exception.

Instance of both Callable and Runnable interfaces can be executed by ExecutorService via submit() method.

Both are functional interfaces and can be used in Lambda expressions since Java8.

You can also convert Runnable to Callable by using the following utility method provided by Executors class. Following is the sample code:

class MyRunnable implements Runnable {
	@Override
	public void run() {
		System.out.println("inside run method");	
	}
}

class External{
    ExecutorService es = Executors.newFixedThreadPool(2);
    Callable<Object> callable = Executors.callable(new MyRunnable());
}

A Future object is used to retrieve the result. A future object task and provides methods to check if the task has been completed or canceled, retrieve the result or cancel the task.

Differences

  • Runnable was introduced in 1.0 whereas Callable was introduced in Java 1.5.
  • A Callable needs to implement call() method while a Runnable needs to implement run() method.
  • A Callable can return a value but a Runnable cannot.
  • A Callable can throw checked exception but a Runnable cannot.
  • A Callable instance returns a result of type V, whereas a Runnable instance doesn’t return a value.
  • If you have a fire and forget task then use Runnable. If you are trying to retrieve a value from a task, then use Callable.
  • Callable can be passed to invokeAll method unlike Runnable.
  • There is one limitation while using Callable interface in Java that you cannot pass it to Thread the way 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. Future.get() is a blocking method and blocks until execution is finished, so you should always call this method with a timeout.