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
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool