Home >Java >javaTutorial >Summary of Java skills: How to read Lambda source code

Summary of Java skills: How to read Lambda source code

WBOY
WBOYforward
2022-04-18 18:13:501565browse

This article brings you relevant knowledge about java, which mainly introduces related issues about how to view Lambda source code. Using Lambda expressions can perform a large number of optimizations on the code. Use several You can do a lot of things with just one line of code. Let’s take a look at it. I hope it will be helpful to everyone.

Summary of Java skills: How to read Lambda source code

Recommended study: "java Video Tutorial"

Everyone knows that Lambda expressions are added in Java8, use Lambda expressions The formula can optimize the code a lot, and you can do a lot of things with just a few lines of code. This chapter takes Lambda as an example. The first section explains its underlying execution principle, and the second section explains the common postures of Lambda flow in work.

1. Demo

First we look at a demo of Lambda expression, as shown below:

The code is relatively simple, just start a new thread to print a sentence, but for the code in the picture () -> System.out.println (“ lambda is run “), I think many students are confused. How does Java Do you recognize this code?

If we change the writing method to anonymous inner class, it will be very clear and everyone can understand it, as shown below:

Does that mean () -> System.out.println (“ lambda is run “) Does this form of code actually create an inner class? In fact, this is the simplest Lambda expression. We cannot see the source code and its underlying structure through IDEA. Here we will introduce several ways to see its underlying implementation.

2. Exception judgment method

We can actively throw exceptions during code execution and print out the stack. The stack will explain its running trajectory. Generally, this method is simple and efficient, and you can basically see Let’s try the hidden code in many cases, as shown below:

From the exception stack, we can see that the JVM automatically creates an internal class for the current class ($ appearing multiple times in the error stack indicates an internal class). During the execution of the code of the internal class, an exception is thrown, but the code shown here is Unknown Source, so we cannot debug it. Under normal circumstances, exceptions Both can expose the code execution path, and we can set breakpoints and run again. However, for Lambda expressions, through the exception judgment method, we only know that there are internal classes, but we cannot see the source code in the internal classes.

3. javap command method

javap is a tool that comes with Java that can view class bytecode files. Computers that have installed the Java basic environment can directly execute the javap command, as shown below:

Among the command options, we mainly use the -v -verbose command to completely output the contents of the bytecode file.

Next we use the javap command to view the Lambda.class file. During the explanation, we will bring some knowledge about class files.

We find the location of Lambda.class in the command window, execute the command: javap -verbose Lambda.class, and then you will see a long list of things, these are called assembly instructions, let’s do it next Let me explain (all reference materials come from the Java Virtual Machine Specification, and will not be cited one by one):

In the assembly instructions, we can easily find a long list of types starting with Constant pool, which we call the constant pool. Official It is called Run-Time Constant Pool in English. We simply understand it as a table filled with constants. The table contains clear numbers and text at compile time, type information of classes, methods and fields, etc. Each element in the table is called cpinfo. cpinfo consists of a unique identification (tag) name. Currently, there are a total of tag types:

Summary of Java skills: How to read Lambda source code

Post Here is part of the picture we parsed:

  1. The words "Constant pool" in the picture represent that the current information is a constant pool;

  2. Each row is a cp_info, #1 in the first column represents the position marked 1 in the constant pool;

  3. The second column of each row is the unique identifier (tag) of cp_info. For example, Methodref corresponds to CONSTANT_Methodref in the above table (the value in the table above corresponds to 10 tag), which means that the current line represents the description information of the method, such as the name of the method, input parameter type, output parameter type, etc. The specific meaning can be found in the Java virtual machine specification. The screenshot of Methodref is as follows:
    Summary of Java skills: How to read Lambda source code

  4. In the third column of each row, if it is a specific value, the specific value will be displayed directly. If it is a complex value, cp_info will be displayed. The reference of , for example, marked red 2 in the picture, refers to the two cp_info at positions 13 and 14. 13 means that the method name is init, 14 means that the method has no return value, and the combination represents the name of the method. And the return type is a parameterless constructor;

  5. The fourth column of each row is the specific value.

For the more important cp_info type, we explain its meaning:

  1. InvokeDynamic represents a dynamic calling method, which we will explain in detail later;
  2. Fieldref represents the description information of the field, such as the name and type of the field;
  3. NameAndType is the description of the field and method type;
  4. MethodHandle method handle, the collective name for dynamic calling methods, during compilation We don't know which method is specific at the time, but we will definitely know which method is being called at runtime;
  5. MethodType is a dynamic method type, and we will only know what its method type is when running dynamically.

We found code similar to this in Ljava/lang/invoke/MethodHandles$Lookup, java/lang/invoke/LambdaMetafactory.metafactory from the three places marked in red in the above figure, both MethodHandles and LambdaMetafactory Important methods under the java.lang.invoke package. The invoke package mainly implements the functions of dynamic languages. We know that the java language is a static compiled language. During compilation, the types of classes, methods, fields, etc. have been determined, and invoke implements a dynamic language, which means that the types of classes, methods, and fields are not known when compiling, and are only known when running.

For example, this line of code: Runnable runnable = () -> System.out.println(“lambda is run”); When the compiler compiles (), the compiler does not know what this bracket does. , only when running will you know that this represents the Runnable.run() method. Many classes in the invoke package are designed to represent these (), which we call method handles (MethodHandler). When compiling, the compiler only knows that this is a method handle, and does not know what method is actually executed. I didn't know it until the time, so the question is, when the JVM executes, how does it know that the () method handle actually executes the Runnable.run() method?

First, let’s take a look at the assembly instructions of the simple method:

From the above figure, we can see the () -> System in the simple method. The () in the out.println(“lambda is run”) code is actually the Runnable.run method.

We trace back to the #2 constant pool, which is marked red 1 in the above picture. InvokeDynamic indicates that this is a dynamic call. The call is the cp_info of the two constant pools. The position is #0:#37. We Look down for #37, which means // run:()Ljava/lang/Runnable. This indicates that when the JVM is actually executed, the Runnable.run() method needs to be called dynamically. From the assembly instructions, we can see that () In fact, it is Runnable.run(). Let’s debug below to prove it.

We found the words LambdaMetafactory.metafactory in 3 places in the above picture. By querying the official documentation, we learned that this method is the key to linking to the real code during execution, so we typed it in the metafactory method. Debug with a breakpoint, as shown below:

Summary of Java skills: How to read Lambda source code

The metafactory method input parameter caller represents the location where the dynamic call actually occurs, invokedName represents the name of the calling method, and invokedType represents the multiple inputs of the call. Parameters and output parameters, samMethodType represents the parameters of the specific implementer, implMethod represents the actual implementer, and instantiatedMethodType is equivalent to implMethod.

To summarize the above:

1: From the simple method of the assembly instruction, we can see that the Runnable.run method will be executed;

2: In the actual operation When the JVM encounters the invokedynamic instruction of the simple method, it will dynamically call the LambdaMetafactory.metafactory method and execute the specific Runnable.run method.

So the specific execution of the Lambda expression value can be attributed to the invokedynamic JVM instruction. It is precisely because of this instruction that although you don’t know what to do when compiling, you can find the specific execution when running dynamically. code.

Next, let’s take a look at the end of the assembly instruction output. We found the internal class found in the exception judgment method, as shown below:

Summary of Java skills: How to read Lambda source code

There are many arrows in the above picture. All the information of the current internal class is expressed clearly layer by layer.

4. Summary

Let us summarize, Lambda expression execution mainly relies on the JVM instruction of invokedynamic. The full path of the class we demonstrate is: demo.eight.Lambda. Interested Students can try it themselves.

Without further ado, the article is over, looking forward to the third series!

Recommended study: "java video tutorial"

The above is the detailed content of Summary of Java skills: How to read Lambda source code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete