Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Runnable is created from Java8 lambda [duplicate]

Tags:

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();
            }
        }
    }
}

So my question is, 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?

thanks.

like image 598
robjwilkins Avatar asked Dec 01 '15 17:12

robjwilkins


People also ask

How do you write runnable as lambda?

Create the Runnable interface reference and write the Lambda expression for the run() method. Create a Thread class object passing the above-created reference of the Runnable interface since the start() method is defined in the Thread class its object needs to be created. Invoke the start() method to run the thread.

Does lambda expression create object?

Yes, any lambda expression is an object in Java.

How are lambda functions compiled?

For Lambda expressions, the compiler doesn't translate them into something which is already understood by JVM. Lambda syntax that is written by the developer is desugared into JVM level instructions generated during compilation, which means the actual responsibility of constructing lambda is deferred to runtime.


1 Answers

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)

like image 82
Pedro Affonso Avatar answered Oct 21 '22 03:10

Pedro Affonso