• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Tim Cooke
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
Saloon Keepers:
  • Piet Souris
Bartenders:

How is the Java ByteCode generated for Lambda Expressions in Java?

 
Ranch Hand
Posts: 31
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How is the Java ByteCode generated for Lambda Expressions in Java?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is an article that explains exactly how lambda expressions are compiled: Java 8 Lambdas - A Peek Under the Hood

And here another (older, from 2012) article from the horse's mouth (Brian Goetz, who led the lambda project at Oracle): Translation of Lambda Expressions

Note: This is not really simple to understand; but the most important thing to know is that it's not as simple as replacing the lambda by an anonymous inner class. Other things are done, involving the invokedynamic bytecode instruction, which make lambdas more efficient than anonymous inner classes. So, that is in itself a good reason to use lambda expressions instead of anonymous inner classes (besides the fact that lambda expressions enable you to write shorter and more readable code compared to anonymous inner classes).
 
Bartender
Posts: 15743
368
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why don't we have a look?

As you can see, the compiler generates an entire class with a constructor and two methods for the anonymous consumer, while it generates one private static method for the lambda expression: lambda$useLambda$0(java.lang.String).

useAnonymousClass() performs new, dup and invokespecial to create an instance of LambdaTest$1 and put it on the operand stack, while useLambda() performs invokedynamic. Both methods then use invokevirtual to call Optional.ifPresent() on whatever is on the operand stack. This means that whatever invokedynamic does with lambda$useLambda$0(java.lang.String), the result must be something that's compatible with Consumer<String>.
 
reply
    Bookmark Topic Watch Topic
  • New Topic