[JVM 1] Class loader + runtime data area

Disclaimer: The JVM series of blogs are my own JVM study notes. Any similarity is purely coincidental.

/**
* @startTime 2021-03-13 08:30
* @endTime 2021-03-13 14:30
* @start P26内存结构概述
* @end P35双亲委派机制
* @efficiency (P35-P25)/1 = 10 * 10.8 = 108分钟/天
* @needDays 3841/108 = 36天
* @overDay 2021-03-13 + 36天 = 2021-04-17
*/

Chapter One Class Loader

One, the role of the class loader subsystem

 

The class loader subsystem is responsible for loading class files from the file system or network. The class files have a specific file identifier at the beginning of the file.

ClassLoader is only responsible for the loading of class files. As for whether it can run, it is determined by the execution engine.

The loaded class information is stored in a memory space called the method area. In addition to class information, the method area will also store runtime constant pool information, and may also include string literals and numeric constants (this part of constant information is the memory mapping of the constant pool part in the class file)

Second, the loading process of the class

1. Load

  • Obtain the binary byte stream that defines this class through the fully qualified name of a class
  • Convert the static storage structure represented by this byte stream into the runtime data structure of the method area
  • Generate a java.lang.Class object representing this class in memory as the access entry for various data of this class in the method area

2. Link

(1) Verify

  • The purpose is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine, to ensure the correctness of the loaded class, and not to endanger the security of the virtual machine itself
  • There are mainly four types of verification: file format verification, metadata verification, bytecode verification, and symbol reference verification

(2) Prepare

  • Allocate memory for the class variable and set the default initial value of the class variable
  • The final modified static is not included here, because final will be allocated during compilation, and initialization will be displayed in the preparation phase
  • The instance variable will not be allocated and initialized here, the class variable will be allocated in the method area, and the instance variable will be allocated to the heap along with the object

(3) Analysis

  • The process of converting symbol references in the constant pool into direct references
  • For example, the display assignment of static code blocks and static variables
  • In fact, the parsing operation is often accompanied by the execution of the JVM after the initialization is performed
  • Symbol reference is a set of symbols to describe the referenced target. The literal form of symbol reference is clearly defined in the Class file format of the "Java Virtual Machine Specification". A direct reference is a pointer to the target, a relative offset, or a handle indirectly located to the target
  • The parsing action is mainly for classes or interfaces, fields, class methods, interface methods, method types, etc. For CONSTANT_Filedref_info, CONSTANT_Class_info, CONSTANT_Methodref_info, etc. in the constant pool.

3. Initialization

  1. The initialization phase is the process of executing the class constructor method <clinit>()
  2. This method does not need to be defined. The javac compiler automatically collects the assignment actions of all class variables in the class and merges the statements in the static code block.
  3. The instructions in the constructor method are executed in the order in which the statements appear in the source file
  4. The <clinit>() method is different from the class constructor. The constructor is <init>() from the perspective of the virtual machine
  5. If the class has a parent class, the JVM will ensure that the <clinit>() of the parent class has been executed before the <clinit>() of the subclass is executed
  6. The virtual machine must ensure that the <clinit>() method of a class is synchronized and locked under multiple threads

Three, code examples

Verify the code example of [the virtual machine must ensure that the <clinit>() method of a class is synchronized and locked under multithreading]

package com.guor.jvm;
 
public class DeadThreadTest {
    public static void main(String[] args) {
        Runnable r = () -> {
            System.out.println(Thread.currentThread().getName() + "开始");
            DeadThread dead = new DeadThread();
            System.out.println(Thread.currentThread().getName() + "结束");
        };
 
        Thread t1 = new Thread(r,"线程1");
        Thread t2 = new Thread(r,"线程2");
        t1.start();
        t2.start();
    }
}
 
class DeadThread{
    static {
        if(true){
            System.out.println(Thread.currentThread().getName() + "初始化当前类");
            while (true){
 
            }
        }
    }
}

The virtual machine must ensure that the <clinit>() method of a class is synchronized and locked under multiple threads

Fourth, the classification of class loaders

There are two types of JVM class loaders, namely Bootstrap ClassLoader and User-Defined ClassLoader.

All class loaders derived from the abstract class ClassLoader are classified as custom class loaders.

1. Start the class loader (boot class loader)

  1. The startup class loader is implemented in C/C++ language, nested inside the JVM
  2. Java's core class libraries are all loaded using a boot class loader, such as String.
  3. No parent loader
  4. It is the parent class loader of the extension class loader and the application class loader
  5. For security reasons, Bootstrap startup class loader only loads classes whose package names start with java, javax, sun, etc. 

2. Extend the class loader

  1. written in java language
  2. Derived from the ClassLoader class
  3. The parent class loader is the startup class loader
  4. Load the class library from the directory specified by the java.ext.dirs system property, or load the class library from the jre/lib/ext subdirectory (extension directory) of the JDK installation directory. If the jar created by the user is placed in this directory, it will also be automatically loaded by the extended class loader

3. Application class loader (system class loader)

  1. written in java language
  2. Derived from the ClassLoader class
  3. The parent class loader is the extended class loader
  4. It is responsible for loading the class library under the path specified by the environment variable classpath or the system property java.class.path
  5. This class loader is the default class loader in the program. Generally speaking, Java application classes are loaded by it
  6. The class loader can be obtained through the ClassLoader.getSystemClassLoader() method

5. Parental delegation mechanism

1. If a class loader receives a class loading request, it will not load it first. Twenty delegates this request to the loader of the parent class to execute;

2. If the parent class loader still has a parent class loader, it will be further delegated upwards, recursively in turn, and the request will eventually reach the top-level startup class loader;

3. If the parent class loader can complete the loading task, it returns successfully. If the parent class cannot complete the loading task, the child loader will load itself with parameters. This is the parent delegation mechanism; 

Six, sandbox security mechanism

Seven, the reference to the class loader

The JVM must know whether a type is loaded by the startup class loader or the user class loader. If a type is loaded by the user class loader, the JVM will save a reference to this class loader in the method area as part of the type information. When resolving references from one type to another, the JVM needs to ensure that the class loaders of these two types are the same.

8. Active and passive use of classes

Seven cases of active use:

  1. Create an instance of the class
  2. Access a static variable of a certain class or interface, or assign a value to the static variable
  3. Call the static method of the class
  4. reflection
  5. Initialize a subclass of a class
  6. The class that is marked as the startup class when the Java virtual machine is started
  7. Dynamic language support provided by JDK7: the analysis result of java.lang.invoke.MethodHandler instance

Except for the above seven cases, other methods of using Java classes are regarded as passive use of the class and will not lead to the initialization of the class.

/**
* @startTime 2021-03-14 08:30
* @endTime 2021-03-14 11:30
* @start P37沙箱安全机制 
* @end P43解决PC寄存器的两个面试问题
* @efficiency (P42-P25)/2 = 9 * 10.8 = 97分钟/天
* @needDays 3841/97 = 40天
* @overDay 2021-03-13 + 40天 = 2021-04-21
*/

Chapter 2 Runtime Data Area

1. The internal structure of the runtime data area

Two, PC register

1. Concept

In the Program Counter Register in the JVM, the name of Register is derived from the register of the CPU, and the register stores on-site information related to instructions. The CPU can only run by loading data into the register.

Here, it is not a physical register in a broad sense. It may be more appropriate to translate it into a PC counter (or instruction counter) (also called a program hook), and it is not easy to cause unnecessary misunderstandings. The PC register in the JVM is an abstract simulation of the physical PC register.

2. Function

The PC register is used to store the address pointing to the next instruction, that is, the instruction code to be executed. The execution engine reads the next instruction.

3. Introduction to PC registers

In the JVM specification, each thread has its own program counter, which is private to the thread, and its life cycle is consistent with the life cycle of the thread.

4. What is the use of using PC registers to store bytecode instruction addresses?

Because the CPU needs to constantly switch between threads, after switching back at this time, it knows where to continue execution.

The bytecode interpreter of the JVM needs to determine what bytecode instruction should be executed next by changing the value of the PC register. 

5. CPU time slice

​/**
* @startTime 2021-03-16 21:00
* @endTime 2021-03-16 22:30
* @start P44虚拟机栈
* @end P52操作数栈
* @efficiency (P52-P25)/4 = 6.75 * 10.8 = 72.9分钟/天
* @needDays 3841/72.9 = 53天
* @overDay 2021-03-13 + 53天 = 2021-05-03
*/

Third, the virtual machine stack

1. The background of the virtual machine stack

Due to the cross-platform design, Java instructions are designed based on the stack. Different platforms have different CPU architectures, so they cannot be designed to be register-based.

The advantage is that it is cross-platform, the instruction set is small, and the compiler is easy to implement, but the disadvantage is that the performance is reduced, and more instructions are needed to achieve the same function.

2. What is the Java virtual machine stack

The Java virtual machine stack is also called the Java stack in the morning. When each thread is created, a virtual machine stack is created, which stores a stack of frames inside, corresponding to the Java method calls.

The life cycle is the same as that of a thread.

Responsible for the operation of Java programs, it saves the local variable table and partial results of the method, and participates in the method call and return.

3. Exceptions that may appear in the stack

(1) A fixed-size Java virtual machine stack is used. If the stack capacity requested by the thread exceeds the maximum capacity allowed by the Java virtual machine stack, the Java virtual machine throws a StackOverflowError exception.

(2) With dynamic stack size, if enough memory cannot be applied for, OutOfMemoryError will be thrown.

4. The operating principle of the stack

5. The internal structure of the stack frame

Fourth, the local variable table

1. The size of the local variable table

The size of the local variable table is determined at compile time, and the size of the local variable table will not be changed during the running of the method.

2、Slot

The storage unit of the local variable table is Slot (variable slot)

Various basic data types and application types that can be known during compilation are stored in the local variable table.

In the local variable table, the 32-bit type only occupies one slot, and the 64-bit type (long+double) occupies two slots.

If the current stack frame is created by the constructor or instance method, then the object reference this will be stored in the slot with index 0, and the remaining parameters will continue to be sorted in the order of the table. This is the real reason why this can be called in constructors and instance methods, but this cannot be called in static methods, because this is stored in the local variable table.

3. Supplementary explanation

The variables in the local variable table are important garbage collection root nodes, as long as the objects directly or indirectly referenced in the local variable table will not be recycled.

Five, the operand stack

1. The operand stack is implemented as an array, last in first out, stored in order, and indexed.

2. Operand stack, in the process of method execution, according to bytecode instructions, write data to the stack or extract data, that is, push into the stack/pop out of the station.

3. The operand stack is mainly used to save intermediate results in the calculation process, and at the same time as a temporary storage space for variables in the calculation process.

4. The operand stack is a work area of ​​the JVM execution engine. When a method is first executed, a new stack frame will also be created, and the operand stack of this method is empty.

5. Although the operand stack is implemented by an array, the operand stack is not used to access the index for data access, but can only be accessed through standard stacking and popping operations.

 

 

Highlights from previous issues:

Summary of Java knowledge system (2021 version)

Summary of basic knowledge of Java multithreading (absolutely classic)

Super detailed springBoot study notes

Summary of common data structures and algorithms

Java design patterns: a comprehensive analysis of 23 design patterns (super detailed)

Summary of Java interview questions (with answers)

Guess you like

Origin blog.csdn.net/guorui_java/article/details/114778965