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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 30-Dec-2019 16:42:30
Advertisements