Java Reference
In-Depth Information
Appendix D. Lambdas and JVM bytecode
You may wonder how the Java compiler implements lambda expressions and how the Java
virtual machine (JVM) deals with them. If you think lambda expressions can simply be
translated to anonymous classes, you should read on. This appendix briefly discusses how
lambda expressions are compiled, by examining the generated class files.
D.1. Anonymous classes
We showed in chapter 2 that anonymous classes can be used to declare and instantiate a class at
the same time. As a result, just like lambda expressions, they can be used to provide the
implementation for a functional interface.
Because a lambda expression provides the implementation for the abstract method of a
functional interface, it would seem straightforward to ask the Java compiler to translate a
lambda expression into an anonymous class during the compilation process. But anonymous
classes have some undesirable characteristics that impact the performance of applications:
The compiler generates a new class file for each anonymous class. The filename usually looks like
ClassName$1 , where ClassName is the name of the class in which the anonymous class appears,
followed by a dollar sign and a number. The generation of many class files is undesirable, because
each class file needs to be loaded and verified before being used, which impacts the startup
performance of the application. If lambdas were translated to anonymous classes, you'd have one new
class file for each lambda.
Each new anonymous class introduces a new subtype for a class or interface. If you had a hundred
different lambdas for expressing a Comparator , that would mean a hundred different subtypes of
Comparator . In certain situations, this can make it harder to improve runtime performance by the
JVM.
D.2. Bytecode generation
A Java source file is compiled to Java bytecode by the Java compiler. The JVM can then execute
the generated bytecode and run the application. Anonymous classes and lambda expressions use
different bytecode instructions when they're compiled. You can inspect the bytecode and
constant pool of any class file using the command
javap -c -v ClassName
 
Search WWH ::




Custom Search