javalambdajava-8

How Runnable is created from Java lambda


I've come across some code which I'm struggling to understand despite a bit of reading. There is a call to a method which takes in two args, one of which is a Runnable. Rather than passing in a Runnable object though there is a lambda.

For example:

public class LambdaTest {

    private final Lock lock = new ReentrantLock();

    @Test
    public void createRunnableFromLambda() {
        Locker.runLocked(lock, () -> {
            System.out.println("hello world");
        });
    }

    public static class Locker {
        public static void runLocked(Lock lock, Runnable block) {
            lock.lock();
            try {
                block.run();
            } finally {
                lock.unlock();
            }
        }
    }
}

Can you explain how a Runnable is created from the lambda, and also please could someone explain the syntax () -> {}. Specifically, what do the () brackets mean?


Solution

  • A Lambda can be used in any place where a functional interface is required. A functional interface is any interface with a single abstract method.

    The lambda syntax used in this case is (arguments) -> {blockOfCodeOrExpression}. The parenthesis can be omitted in the case of a single argument, and the braces can be omitted in the case of a single command or expression.

    In other words, () -> System.out.println("hello world"); is equivalent* here where a Runnable is expected to

     new Runnable(){      
       @Override
       public void run(){
         System.out.println("Hello world one!");
       }
     };
    

    *(I'm pretty sure that it is not bytecode-equivalent, but is equivalent in terms of functionality)