Tuesday 4 August 2015

Textual Representation of logo

How Does Lambdas Work In Java

In this post , i will show how lambdas in java work , with a simple example .Consider the following code snipped using java lambda .
package java8Test;

import java.io.File;
import java.io.FileReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LambdaTest2 {
  public static void main(String[] args) {
      ExecutorService service = Executors.newSingleThreadExecutor();
      service.submit(()-> {
        File f = new File("abcd.txt");
        FileReader reader = new FileReader(f);
        //use reader to read stuff
        return null ;
The above code compiles fine , now if you remove return statement(which seems redundant here) from above code , it fails to compile with following error :
Unhandled exception type FileNotFoundException
Reason for this behavior is , ExecutorService's submit method has two overloaded versions . One takes Callable , and the other one takes Runnable , Both methods have no arguments .

So , which one the java compiler chooses ?

It looks for return type as well . When you write return statement , it creates Callable and when you return nothing , it creates Runnable . Since Runnable does not throw Checked Exceptions , that is why you get compile time errors in the code .

You can explicitly cast it to Callable by using cast operator like this :
service.submit((Callable)()-> {
You can add marker interfaces also in the cast like this :
Callable calls = (Callable & Serializable) () -> { return null; };
Lambda Removes a lot of boilerplate code , but it might behave differently if you don't know how it works .
You can go to original link here