Since Callable is a functional interface, Java 8 onward it can also be implemented as a lambda expression. This post shows how you can implement Callable interface as a lambda expression in Java.
Suppose you want to have a callable where string is passed and it returns the length of the string. 
In this Java code a thread pool of 2 threads is created and then submit method is called with callable 
object as parameter.
Java Code
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableLambda {
  public static void main(String args[]){
    ExecutorService es = Executors.newFixedThreadPool(2);
    getLength(es, "executor");
    getLength(es, "executor service");
    getLength(es, "Scheduled executor service");
    getLength(es, "executors");
    getLength(es, "fork join");
    getLength(es, "callable");    
  }
    
  public static void getLength(ExecutorService es, final String str){
    // callable implemented as lambda expression
    Callable<String> callableObj = () -> {
      StringBuffer sb = new StringBuffer();
      return (sb.append("Length of string ").append(str).append(" is ").
              append(str.length())).toString();
    };
        
    // submit method
    Future<String> f = es.submit(callableObj);
    
    try {
      System.out.println("" + f.get());
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Output
Length of string executor is 8 Length of string executor service is 16 Length of string Scheduled executor service is 26 Length of string executors is 9 Length of string fork join is 9 Length of string callable is 8
Also, if you noticed the try-catch block in the code, multi catch statement from Java 7 is used here.
That's all for this topic Java Lambda Expression Callable Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-
No comments:
Post a Comment