Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the JVM class loading mechanism and parent delegation model

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people have no idea about what the JVM class loading mechanism and parent delegation model are. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

How does the Java program run, and how does it output results from a .java source file to the console?

To answer similar questions, you need to learn the virtual machine class loading mechanism.

The overall process

All classes in Java must be loaded into jvm in order to run, this loading work is done by the class loader in jvm, the essence of the work of class loader is to read the class files from the hard disk to memory, JVM in loading classes, are through the ClassLoader loadClass () method to load class, loadClass uses parent delegation model.

There are a lot of unfamiliar nouns in the above process, this article is to analyze these nouns, when you look back at this sentence will suddenly become clear.

Declaration cycle of the class

First parse this diagram, which shows the entire declaration cycle of the class. The class consists of seven stages from being loaded into the virtual machine memory to unloading the memory, in which the verification, preparation and parsing phases are collectively referred to as connections.

The order of the five phases of loading, validation, preparation, initialization, and unloading is determined, while the parsing phase is not necessarily, which in some cases can start after the initialization phase to support the runtime binding (dynamic or late binding) of the Java language.

Loading

Loading is easy to say, but for JVM, it is a complex process, that is, the class loading mechanism of the virtual machine: the virtual machine loads the data describing the class from the Class file into memory, and verifies, transforms, parses and initializes the data, and finally forms the Java type that can be directly used by the virtual machine.

Load

The "loading" mentioned here is a stage of the "class loading" process. "class loading" describes the whole process. "loading" only represents the first stage of "class loading". There are three things that need to be done:

Get 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 that represents the class in memory as the access entry for all kinds of data of the class in the method area

All this actually accomplishes one thing: generate a Class object in memory based on the name of a class (fully qualified name). Note that the Class object is not the object from the keyword new, but that Class is a type that represents the runtime type information of an object.

The next three phases are all Linking. Part of the content of the load phase (such as part of the bytecode file format verification action) is crossed, the load phase has not yet been completed, and the connection phase may have begun.

Connect-verify

The purpose of verification is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and does not compromise the security of the virtual machine itself. If it is verified that the input byte stream does not conform to the constraints of the Class file format, the virtual machine will throw a java.lang.VerifyError exception or its subclass exception.

The verification phase roughly completes four stages of verification: file format verification, metadata verification, bytecode verification, symbol reference verification.

Connect.-ready.

The preparation phase is the extreme of formally allocating memory for class variables (static-decorated variables) and setting the initial values of class variables, and the memory used by these variables will be allocated in the method area. Note that only class variables are included in memory allocation at this time, not instance variables, which will be allocated in the Java heap along with the object when the object is instantiated.

And the initial values mentioned here refer to zero values, and each basic data type has a corresponding zero value.

Suppose a class variable is defined as:

Public static int value = 123

Then the initial value of this variable after the preparation phase is 0 instead of 123, and the action of assigning value to 123 will not be performed until the initialization phase.

Connect-parse

The parsing phase is the process that the virtual machine replaces the symbolic references in the constant pool with direct references.

Symbolic reference: only contains semantic information, does not involve the specific implementation, with a set of symbols to describe the reference target, is a literal quantity; symbolic reference has nothing to do with the memory layout implemented by the virtual machine, and the target of the reference is not necessarily loaded into memory.

Direct reference: closely related to the specific implementation, it is a pointer directly to the target; a direct reference is a pointer that can directly point to the target, a relative offset, or a handle that can be located indirectly to the target. If there is a direct reference, the target of the reference must already exist in memory.

Initialization

The initialization phase actually begins to execute the Java program code (or bytecode) defined in the class

In the preparation phase, the variables have been assigned the initial values required by the system, while in the initialization phase, class variables and other resources are initialized according to the programmer's subjective plan through the program.

That is, we usually understand assigning initial values and executing static blocks of code.

Class loader

Class and class loader

For any class, the class loader that loads it and the class itself need to establish its uniqueness in the Java virtual machine. Each class loader has an independent class namespace.

Comparing whether two classes are "equal" is meaningful only if the two classes are loaded by the same class loader, otherwise, even if the two classes come from the same Class file and are loaded by the same virtual machine, the two classes must not be equal as long as they are loaded by different class loaders.

Types of loaders (from the developer's point of view)

Launch class loader (Bootstrap ClassLoader): responsible for storing the

In the\ lib directory, or in the path specified by the-Xbootclasspath parameter, and is recognized by the virtual machine (identified only by file name, such as rt.jar, class libraries that do not match the name will not be loaded even if placed in the lib directory) class libraries are loaded into the virtual machine memory

Extension class loader (Extension ClassLoader): responsible for loading

All class libraries in the\ lib\ ext directory or in the path specified by the java.ext.dirs system variable

Application class loader (Application ClassLoader): also known as the system class loader, responsible for loading the class libraries specified on the user classpath (ClassPath). If you have not customized your own class loader in your application, this is generally the default class loader in the program.

Parental delegation model

Parent delegation model of class loader

The hierarchical relationship between class loaders shown in the figure above is called the parent delegation model of the class loader.

Except for the top-level startup class loader, the parent delegate model should have its own parent class loader. The parent-child relationships between class loaders here are generally not implemented as inherited relationship classes, but instead use composite relationships to reuse the code of the parent loader.

How the parent delegate model works: if a class loader receives a request for class loading, it will not attempt to load the class itself at first, but delegate the request to the parent class loader to complete it. This is true for every level of class loader, so all load requests should eventually be passed to the top-level startup class loader. Only when the parent loader reports that it cannot complete the load request (the required class is not found in its search scope), the child loader will try to load itself.

Why use the parent delegation model

To borrow an example: a hacker customizes a java.lang.String class, which has the same function as the String class of the system, but with minor modifications to a function. Such as the equals function, which is often used if hackers add some "virus code" to this function. And add it to JVM through a custom class loader. At this point, if there is no parent delegation model, then JVM may mistakenly think that the java.lang.String class customized by the hacker is the String class of the system, causing the "virus code" to be executed.

With the parent delegation model, hacker-customized java.lang.String classes will never be loaded into memory. Because the top class loader loads the java.lang.String class of the system first, the custom class loader cannot load the java.lang.String class eventually.

That is to say, no matter which class loader loads an existing class in a system, it is finally delegated to the startup class loader at the top of the model, so the system is the same class in all kinds of class loader environment of the program.

How to realize the Parental delegation Model

The code to implement parent delegation is in the loadClass () method of java.lang.ClassLoader: first check whether it has been loaded, if not, call the loadClass () method of the parent loader, and use the startup class loader as the parent loader by default if the parent loader is empty. If the parent loader fails to load, a ClassNotFoundException exception is thrown before calling its own findClass () method to load. (after looking at the source code, it is found that the throw exception here has been swallowed, and catch will not do anything after that.)

Destroy the parental delegation model

The parent delegation model is not a mandatory constraint model, but rather the implementation of the class loader recommended by Java designers to developers. Most class loaders follow this model, but the parent delegation model can also be broken, not bad, but in the case of sufficient meaning and reason, break through the existing rules to create, to achieve specific functions.

Three ways to destroy the parental delegation model

Override the loadClass () method

Reverse use of the classloader to introduce the thread context classloader

Pursue the dynamic nature of programs: hot code replacement, module hot deployment and other technologies

After reading the above, have you mastered the JVM class loading mechanism and what the parent delegation model is? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report