search
HomeJavajavaTutorialSummary of Java skills: How to read Lambda source code

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. If there is any infringement, please contact admin@php.cn delete
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool