Implement Callable interface

Java 11 Certification Practice Questions (For the complete list, refer

Section: Concurrency

Objective: Create worker threads using Runnable and Callable, and manage concurrency using an ExecutorService and java.util.concurrent API

In this article, we discuss about implementing the Callable interface.

About Callable

The java.util.concurrent.Callable interface defines a call() method that returns a value and can throw a checked exception.

Here is the definition of the Callable interface:

@FunctionalInterface public interface Callable<V> {
    V call() throws Exception;

The ExecutorService includes an overloaded version of the submit() method that takes a Callable object and
returns a generic Future instance.

Runnable vs Callable

The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. However, there are some differences.

  • A Callable cannot be passed to the Thread class constructor, only a Runnable can be passed to the Thread class constructor. For example, new Thread(Callable) is not valid.
  • In the case of Runnable, there is no way to propagate checked exceptions as the run() method does not have the throws clause. However, Callable can be used to throw checked exceptions as the call() method has a throws clause.
  • Also, a Runnable, does not return a result. However, a Callable can be used to execute tasks that return a result that can be collected asynchronously later.

How do we implement Callable using lambda expressions?

As Callable is a functional interface, it can be implemented using a lambda expression that takes no parameters and returns a generic type.

Here is an example of using the Callable interface to calculate the sum of even numbers from 1 to 10.

public class CallableTest {
	   public static void main(String args[]) throws InterruptedException {
	      ExecutorService executorService = Executors.newSingleThreadExecutor();
	      Callable callable = () -> {  
	         int n = 0;
	         for(int i = 0; i < 10; i++) {
	        	 if(i % 2 == 0) {
	        		 n+= i;
	         return n;
	      Future<Integer> future = executorService.submit(callable);
	      try {
	         Integer result = future.get(); 
	      } catch(ExecutionException e) {

In the above code, the submit() method of the ExecutorService is passed a Callable object. This object is implemented as a lambda expression. Inside the expression body, the sum of even numbers is calculated and returned.


Is the following a valid Callable expression?

 Callable callable = () -> {return null;};


Yes, this is a valid lambda expression for Callable because it takes no arguments and returns a value, even though it is null.

Leave a Reply

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