search
HomeJavajavaTutorialIn-depth understanding of Java loaders

In-depth understanding of Java loaders

Nov 29, 2019 pm 01:44 PM
javaclass loader

In-depth understanding of Java loaders

1. Classes and Class Loaders

Class loader: The first step in the loading phase, through the fully qualified name of a class To load the binary byte stream of this class into the jvm.

Classes and class loaders: The uniqueness of any class is determined by itself and the class loader that loads it. Whether two classes are equal depends on the premise that they are loaded by the same class loader.

The jvm virtual machine includes two class loaders: one is the startup class loader (Bootstrap ClassLoader), which is implemented in C; the other is all others implemented in java Class loader.

From a java program perspective:

1) Start the class loader: Responsible for loading classes in the \lib directory or in the path specified by the -Xbootclasspath parameter, in addition to requiring files The name is recognized by the virtual machine. If it is not recognized by the jvm, it cannot be loaded.

2) Extension class loader: Responsible for loading all class libraries in the \lib\exit directory or in the path specified by the java.exit.dirs system variable.

3) Application class loader (system class loader): It is the return value of the getSystemClassloader() method in Classloader. Responsible for loading the class library specified on the user class path. If there is no custom class loader in the application, this will be the default class loader in the program.

Free online video teaching: java video tutorial

2. Parental delegation model

In-depth understanding of Java loaders

Except for the top-level startup class loader, all other class loaders have their own parent class loaders. The parent-child relationship is not implemented through inheritance, but through a combination relationship to reuse the parent class loader.

Working process: The class loader receives the class loading request –> delegates the request to the parent class loader (until the top-level class loader is started) –> the parent class attempts to load, and the loading failure is fed back to the child Class loader –> The subclass loader attempts to load the

Benefits of the parent delegation model: ensuring the stability of the Java underlying API and avoiding multiple differences caused by loading custom classes with the same name (Object) as the basic class Classes (Object) with the same name, causing confusion in the basic behavior of Java.

Parental delegation model source code:

The method adds a synchronization lock to ensure thread safety. First check whether the class has been loaded. If not, call the parent class loader. loadClass() method, if the parent class loader is empty, it means the startup class loader, then the startup class loader is called.

If the parent class fails to load, ClassNotFoundException will be thrown, and then call your own findClass() method to load it.

protected Class<?> loadClass(String name, boolean resolve)
    throws ClassNotFoundException
{
    //同步锁
    synchronized (getClassLoadingLock(name)) {
        // 首先检车这个类是不是已被加载
        Class<?> c = findLoadedClass(name);
        if (c == null) {
            long t0 = System.nanoTime();
            try {
                if (parent != null) {
                    //如果父类不为空则调用父类加载器的loadClass方法
                    c = parent.loadClass(name, false);
                } else {
                    //没有父类则默认调用启动类加载器加载
                    c = findBootstrapClassOrNull(name);
                }
            } catch (ClassNotFoundException e) {
                //如果父类加载器找不到这个类则抛出ClassNotFoundException
            }


            if (c == null) {
                // 父类加载器失败时调用自身的findClass方法加载
                long t1 = System.nanoTime();
                c = findClass(name);


                //记录
                sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                sun.misc.PerfCounter.getFindClasses().increment();
            }
        }
        if (resolve) {
            resolveClass(c);
        }
        return c;
    }
}

3. Destruction of the Parental Delegation Model

1. The first destruction of the Parental Delegation Model

appeared in JDK1. After 2, while the class loader and abstract class java.lang.ClassLoader already existed.

Therefore, for forward compatibility, a new protected method findClass was added to ClassLoader after JDK1.2. Users write their own class loading logic in the findClass method instead of overriding the loadClass method to ensure that custom class loading complies with the parent delegation model.

2. The second destruction

The model itself is defective. Parental delegation can ensure the unification of the base classes of each class loader. This is when the user code calls the base class. It does not apply if the base class calls back to the user code. For example, in scenarios involving SPI, load the required SPI code.

For an introduction to the SPI mechanism, please refer to other articles.

In order to solve this problem, the thread context loader (Thread Context ClassLoader) is introduced. This class loader can be set through the setContextClassLoader() method in the java.lang.Thread class. If the thread is not created when The setting will be inherited from the parent thread. If there is none globally, the default is the application class loader. This loader can be used to complete the action of the parent class loader requesting the child class loader to load.

3. The third damage

is caused by the pursuit of program dynamics, such as hot deployment, hot replacement, etc.

For example, in the modular standard OSGi R4.2, the tree structure of parental delegation has been changed into a more complex network structure.

Recommended java article tutorials: java introductory tutorial

The above is the detailed content of In-depth understanding of Java loaders. 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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment