Implement Callable as lambda expressions

Java 11 Certification Practice Questions (For the complete list, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)

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 Callable using lambda expressions.

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.

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(); 
	         System.out.println(result);
	      } catch(ExecutionException e) {
	         e.printStackTrace();
	      }
	      executorService.shutdown();
	   }
	}

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.

Quiz

Is the following a valid Callable expression?

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

Answer

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 *