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.
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.
Yes, any lambda expression is an object in Java.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With