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

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;

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 () method. Therefore, the action of assigning value to 123 will only be executed during the initialization phase.

public static final int value=123;

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
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Java Application Performance Monitoring (APM) ToolsJava Application Performance Monitoring (APM) ToolsJul 24, 2025 am 03:37 AM

Common JavaAPM tools include NewRelic, DatadogAPM, AppDynamics, SkyWalking, Pinpoint and Prometheus Grafana Micrometer combinations; whether APM is required depends on system lag, complex microservice calls, performance details and optimization requirements; APM should consider deployment methods, learning costs, performance impact, cost and integration capabilities; when using them, you should pay attention to reasonable configuration, sampling rate, alarm rules, and analyze the root cause in combination with code.

Building Reactive Java Applications with RxJavaBuilding Reactive Java Applications with RxJavaJul 24, 2025 am 03:35 AM

1.RxJava is a responsive framework based on observer pattern and functional programming, suitable for handling asynchronous and non-blocking tasks. 2. Core types include Observable, Flowable, Single, etc., which are used to represent different forms of data flow. 3. Data conversion and combination are performed through operators such as map, filter, and flatMap to simplify complex logic. 4. Use Schedulers.io(), Schedulers.computation(), AndroidSchedulers.mainThread() and other schedulers to control thread switching. 5. Specify the data flow start thread through subscribeOn, obse

Implementing a Thread-Safe Singleton in JavaImplementing a Thread-Safe Singleton in JavaJul 24, 2025 am 03:35 AM

When using double check lock to implement lazy loading singletons, the volatile keyword is required to ensure thread visibility and prevent instruction re-arrangement; 2. It is recommended to use static internal classes (BillPugh scheme) to implement thread-safe lazy loading singletons, because the JVM ensures thread safety and no synchronization overhead; 3. If you do not need lazy loading, you can use static constants to implement simple and efficient singletons; 4. When serialization is involved, enumeration method should be used, because it can naturally prevent multiple instance problems caused by reflection and serialization; in summary, general scenarios prefer static internal classes, and serialized scenarios to select enumerations. Both have the advantages of thread safety, high performance and concise code.

Comparing Java, Kotlin, and Scala for Backend DevelopmentComparing Java, Kotlin, and Scala for Backend DevelopmentJul 24, 2025 am 03:33 AM

Kotlinoffersthebestbalanceofbrevityandreadability,Javaisverbosebutpredictable,andScalaisexpressivebutcomplex.2.Scalaexcelsinfunctionalprogrammingwithfullsupportforimmutabilityandadvancedconstructs,KotlinprovidespracticalfunctionalfeatureswithinanOOPf

Managing Dependencies in a Large-Scale Java ProjectManaging Dependencies in a Large-Scale Java ProjectJul 24, 2025 am 03:27 AM

UseMavenorGradleconsistentlywithcentralizedversionmanagementandBOMsforcompatibility.2.Inspectandexcludetransitivedependenciestopreventconflictsandvulnerabilities.3.EnforceversionconsistencyusingtoolslikeMavenEnforcerPluginandautomateupdateswithDepend

Mastering Java 8 Streams and LambdasMastering Java 8 Streams and LambdasJul 24, 2025 am 03:26 AM

The two core features of Java8 are Lambda expressions and StreamsAPI, which make the code more concise and support functional programming. 1. Lambda expressions are used to simplify the implementation of functional interfaces. The syntax is (parameters)->expression or (parameters)->{statements;}, for example (a,b)->a.getAge()-b.getAge() instead of anonymous internal classes; references such as System.out::println can further simplify the code. 2.StreamsAPI provides a declarative data processing pipeline, the basic process is: create Strea

Java Security Tokenization and EncryptionJava Security Tokenization and EncryptionJul 24, 2025 am 03:24 AM

SecurityToken is used in Java applications for authentication and authorization, encapsulating user information through Tokenization to achieve stateless authentication. 1. Use the jjwt library to generate JWT, select the HS256 or RS256 signature algorithm and set the expiration time; 2. Token is used for authentication, Encryption is used for data protection, sensitive data should be encrypted using AES or RSA, and passwords should be stored with hash salt; 3. Security precautions include avoiding none signatures, setting the expiration time of tokens, using HTTPS and HttpOnlyCookies to store tokens; 4. In actual development, it is recommended to combine SpringSecurity and

The role of `var` for Local-Variable Type Inference in JavaThe role of `var` for Local-Variable Type Inference in JavaJul 24, 2025 am 03:23 AM

var was introduced in Java 10 for local variable type inference, to determine the type during compilation, and maintain static type safety; 2. It can only be used for local variables in methods with initialized expressions, and cannot be used for fields, parameters or return types; 3. Non-initialization, null initialization and lambda expression initialization are prohibited; 4. It is recommended to use them when the type is obvious to improve simplicity and avoid scenarios that reduce readability. For example, types should be explicitly declared when complex methods are called.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor