Home Java javaTutorial Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

Aug 24, 2019 pm 03:14 PM
jvm

In the previous article, we explained Class files. In this article, we will talk about how the virtual machine loads these Class files? What happens to the information in the Class file after it enters the virtual machine? This involves the class loading mechanism.

The class loading mechanism is to load the class data from the Class file into the memory, verify the data, convert, parse and initialize it, and finally form a java type that can be directly used by the virtual machine. This series of processes are completed during the running of the program.

Class loader

The class loader is the part in the red box in the figure below. It obtains the binary bytes describing this class through the fully qualified name of a class. Stream, thereby dynamically loading java classes into the memory space of the JVM.

Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

Applicable scenarios

For the loading phase of a non-array class, you can use the system This can be done by the provided boot class loader, or it can be done by a user-defined class loader.
For the array class, it is created directly by the java virtual machine without going through the class loader.

Parental delegation mechanism

Parental delegation mechanism is a method used by class loading. If a class loader receives a class loading request, it will not try to load the class itself first, but delegates the request to the parent class loader to complete. This is true for every level of class loader. Only when the parent loader reports that it cannot complete the request, the child loader will try to load it by itself.

Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

Analogy to reality: Xiao Ming wants to buy a toy excavator, but he is too embarrassed to say it directly. So, the following conversation took place.

Xiao Ming asked his father: Dad, do you have an excavator?
Dad said: No
Then Dad asked Grandpa: Dad, Dad, do you have an excavator?
Grandpa said: No
Then Grandpa asked Great Grandpa: Dad, Dad, do you have an excavator?
Grandpa said: Me neither. Let your great-grandson buy one.
As a result, Xiao Ming happily bought a toy excavator by himself.

Category

The startup class loader is implemented in C and is part of the virtual machine itself.
Other class loaders are implemented in the Java language, independent of the virtual machine, and all inherit from the abstract class java.lang.ClassLoader.

Benefits

Take the String class as an example. Even if the user writes an implementation of the String class himself, when loading this class, it will only be delegated to the startup class loader to load the original String class in the JDK, and the custom String class will never be loaded. transfer. This ensures the security of the system.

When is class loading performed?

There are and only the following 5 ways to load a class immediately

(1) When using new to instantiate an object; reading or configuring the static fields of a class (modified by final, already being compiled) (except when the result is put into the static field of the constant pool); when calling a static method of a class.

(2) When using the method of the java.lang.reflect package to make a reflective call to the class. If the class has not been initialized, its initialization needs to be triggered first.

(3) When initializing a class, if it is found that its parent class has not been initialized, you need to trigger the initialization of its parent class first.

(4) When the virtual machine starts, the user needs to specify a main class to be executed (the class containing the main() method), and the virtual machine will first initialize the main class

Detailed description of the class loading process

The class loading process is divided into 5 steps. Most of them are dominated and controlled by the virtual machine, except for the following two situations:

In the loading phase

Developers can participate through a custom class loader

In The initialization phase

will execute the developer's code to initialize class variables and other resources

1. Loading

Things that the virtual machine needs to complete:
(1) Obtain the binary byte stream that defines this class through the fully qualified name of a class.
(2) Convert the static storage structure represented by this byte stream into the runtime data structure of the method area.
(3) Generate a java.lang.Class object representing this class in memory as an access entry for various data of this class in the method area.

Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism

2. Verification

The purpose of verification is to ensure that the Class file The information contained in the byte stream meets the requirements of the current virtual machine and will not endanger the security of the virtual machine itself.
It is divided into 4 steps: file format verification, metadata verification, bytecode verification, and symbol reference verification. Among them, file format verification operates directly on the byte stream, and the remaining three items are performed in the method area.

3. Preparation

This stage is the stage to formally allocate memory for class variables and set the initial value of class variables. It is allocated in the method area. There are two points to note:

(1) At this time, only memory allocation is performed for class variables (variables modified by static), not object variables. Memory is allocated to an object when the object is instantiated and is allocated to the Java heap along with the object.

(2) If a class variable is not final modified, its initial value is the zero value of the data type. For example, the int type is 0, and the boolean type is false. Give an example to illustrate:

public static int value=123;
Copy after login

The initial value after the preparation phase is 0 instead of 123, because no java method has been executed at this time, and the putstatic instruction that assigns the value to 123 is after the program is compiled. , stored in the class constructor < clinit >() method. Therefore, the action of assigning value to 123 will only be executed during the initialization phase.

public static final int value=123;
Copy after login

Because there is final at this time, the value has been assigned to 123 during the preparation stage.

4. Parsing

The parsing phase is the process in which the virtual machine replaces the symbol references in the constant pool with direct references. Classes or interfaces, fields, class methods, interface methods, etc. can be parsed.

What is a symbolic reference:

A symbolic reference is a string containing class information, method name, method parameters and other information. It is used in the method table of the class for actual use. Find the corresponding method.

What is a direct reference:

The direct reference is the offset, which can be found directly in the memory area of ​​the class The starting position of the method bytecode. The
symbol reference tells you some characteristics of this method. You need to use these characteristics to find the corresponding method. Direct quotation means directly telling you where this method is.

5. Initialization

This stage is used to initialize class variables and other resources. It is the execution class constructor() The method process is when the Java program code defined in the class actually begins to be executed.

The above is a detailed explanation of the JAVA virtual machine class loading mechanism. For more related questions, please visit the PHP Chinese website: JAVA Video Tutorial

The above is the detailed content of Detailed introduction to JAVA Virtual Machine (JVM) (5) - Class loading mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A distributed JVM monitoring tool, very practical! A distributed JVM monitoring tool, very practical! Aug 15, 2023 pm 05:15 PM

This project is designed to facilitate developers to monitor multiple remote host JVMs faster. If your project is Spring boot, it is very easy to integrate. Just introduce the jar package. If it is not Spring boot, don’t be discouraged. You can quickly initialize a Spring boot program and introduce it yourself. Jar package is enough

Detailed explanation of JVM command line parameters: the secret weapon to control JVM operation Detailed explanation of JVM command line parameters: the secret weapon to control JVM operation May 09, 2024 pm 01:33 PM

JVM command line parameters allow you to adjust JVM behavior at a fine-grained level. The common parameters include: Set the Java heap size (-Xms, -Xmx) Set the new generation size (-Xmn) Enable the parallel garbage collector (-XX:+UseParallelGC) Reduce the memory usage of the Survivor area (-XX:-ReduceSurvivorSetInMemory) Eliminate redundancy Eliminate garbage collection (-XX:-EliminateRedundantGCs) Print garbage collection information (-XX:+PrintGC) Use the G1 garbage collector (-XX:-UseG1GC) Set the maximum garbage collection pause time (-XX:MaxGCPau

JVM memory management key points and precautions JVM memory management key points and precautions Feb 20, 2024 am 10:26 AM

Key points and precautions for mastering JVM memory usage JVM (JavaVirtualMachine) is the environment in which Java applications run, and the most important one is the memory management of the JVM. Properly managing JVM memory can not only improve application performance, but also avoid problems such as memory leaks and memory overflows. This article will introduce the key points and considerations of JVM memory usage and provide some specific code examples. JVM memory partitions JVM memory is mainly divided into the following areas: Heap (He

Analysis of the functions and principles of JVM virtual machine Analysis of the functions and principles of JVM virtual machine Feb 22, 2024 pm 01:54 PM

An introduction to the analysis of the functions and principles of the JVM virtual machine: The JVM (JavaVirtualMachine) virtual machine is one of the core components of the Java programming language, and it is one of the biggest selling points of Java. The role of the JVM is to compile Java source code into bytecodes and be responsible for executing these bytecodes. This article will introduce the role of JVM and how it works, and provide some code examples to help readers understand better. Function: The main function of JVM is to solve the problem of portability of Java programs on different platforms.

Java Error: JVM memory overflow error, how to deal with and avoid Java Error: JVM memory overflow error, how to deal with and avoid Jun 24, 2023 pm 02:19 PM

Java is a popular programming language. During the development of Java applications, you may encounter JVM memory overflow errors. This error usually causes the application to crash, affecting the user experience. This article will explore the causes of JVM memory overflow errors and how to deal with and avoid such errors. What is JVM memory overflow error? The Java Virtual Machine (JVM) is the running environment for Java applications. In the JVM, memory is divided into multiple areas, including heap, method area, stack, etc. The heap is used to store created objects

Java program to check if JVM is 32-bit or 64-bit Java program to check if JVM is 32-bit or 64-bit Sep 05, 2023 pm 06:37 PM

Before writing a java program to check whether the JVM is 32-bit or 64-bit, let us first discuss about the JVM. JVM is a java virtual machine, responsible for executing bytecode. It is part of the Java Runtime Environment (JRE). We all know that java is platform independent, but JVM is platform dependent. We need separate JVM for each operating system. If we have the bytecode of any java source code, we can easily run it on any platform due to JVM. The entire process of java file execution is as follows - First, we save the java source code with .java extension and the compiler converts it into bytecode with .class extension. This happens at compile time. Now, at runtime, J

How to adjust JVM heap memory size efficiently? How to adjust JVM heap memory size efficiently? Feb 18, 2024 pm 01:39 PM

JVM memory parameter settings: How to reasonably adjust the heap memory size? In Java applications, the JVM is the key component responsible for managing memory. Among them, heap memory is used to store object instances. The size setting of heap memory has an important impact on the performance and stability of the application. This article will introduce how to reasonably adjust the heap memory size, with specific code examples. First, we need to understand some basic knowledge about JVM memory. The JVM's memory is divided into several areas, including heap memory, stack memory, method area, etc. in

Demystifying the working principle of JVM: In-depth exploration of the principles of Java virtual machine Demystifying the working principle of JVM: In-depth exploration of the principles of Java virtual machine Feb 18, 2024 pm 12:28 PM

Detailed explanation of JVM principles: In-depth exploration of the working principle of the Java virtual machine requires specific code examples 1. Introduction With the rapid development and widespread application of the Java programming language, the Java Virtual Machine (JavaVirtualMachine, referred to as JVM) has also become indispensable in software development. a part of. As the running environment for Java programs, JVM can provide cross-platform features, allowing Java programs to run on different operating systems. In this article, we will delve into how the JVM works

See all articles