How can we write Callable as a lambda expression in Java?


A Callable interface defined in java.util.concurrent package. An object of Callable returns a computed result done by a thread in contrast to a Runnable interface that can only run the thread. The Callable object returns Future object that provides methods to monitor the progress of a task executed by a thread. An object of the Future used to check the status of a Callable interface and retrieves the result from Callable once the thread has done.

In the below example, we can write a Callable interface as a Lambda Expression.

Example

import java.util.concurrent.*;

public class LambdaCallableTest {
   public static void main(String args[]) throws InterruptedException {
      ExecutorService executor = Executors.newSingleThreadExecutor();
      Callable c = () -> {   // Lambda Expression
         int n = 0;
         for(int i = 0; i < 100; i++) {
            n += i;
         }
         return n;
      };
      Future<Integer> future = executor.submit(c);
      try {
         Integer result = future.get(); //wait for a thread to complete
         System.out.println(result);
      } catch(ExecutionException e) {
         e.printStackTrace();
      }
      executor.shutdown();
   }
}

Output

4950

Updated on: 13-Jul-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements