A detailed description of the JVM class loading mechanism (ii) class loader and parental delegation model

Source: Internet
Author: User

in the previous article A detailed description of the JVM class loading mechanism (a) during the JVM class loading process, the first phase of the class loading mechanism is loaded with the following tasks:

1. Obtain a binary byte stream (class file) that defines this class through the fully qualified name of a class (package name and class name). The method can be obtained through jar package, war package, network acquisition, JSP file generation and so on.

2. Transform the static storage structure represented by this byte stream into the runtime data structure of the method area. This simply transforms the data structure and does not combine the figures. (The method area is used to store the loaded class information, constants, static variables, compiled code of the run-time memory area)

3. Generate a Java.lang.Class object representing this class in memory as the access entry for various data of this class in the method area. This class object is not specified in the Java heap memory, it is more special, although the object, but stored in the method area.


Where the code block that implements the first work is called the class loader .


The function of class loader is not only to implement class loading, but also to determine the "equality" of the class, which is related to the return result of the Java "Equality" decision method, and it can be determined that two classes are equal only if the following three classes "equal" criteria are satisfied.

1. two classes from the same class file

2, two classes are loaded by the same virtual machine

3, two classes are loaded by the same ClassLoader


J Ava "Equality" decision related methods:

1. Determine whether the reference to two instance objects points to the same instance object in memory, using the Equals () method of the Class object, Obj1.equals (OBJ2);
2. Determine if the instance object is an instance object of a class, interface, or its subclasses, sub-interfaces, using the Isinstance () method of the Class object, Class.isinstance (obj);

3, judge whether the instance object is a class, an instance of the interface, using the instanceof keyword, obj instanceof class;
4, judge whether a class is another class itself or its subclasses, sub-interfaces, you can use the class object's IsAssignableFrom () method, Class1.isassignablefrom (Class2).


The JVM class loader is categorized in detail:

1, Bootstrap ClassLoader: Start the ClassLoader, also known as the root class loader, it is responsible for loading the core class library of JAVA, loading core class libraries such as Rt.jar (which contains system, string, and so on) in the (%java_home%/lib) directory . The root ClassLoader is very special, it is not a subclass of Java.lang.ClassLoader, it is implemented internally by C + + in the JVM itself and is not implemented in Java.

2. Extension ClassLoader: The extension classloader, which is responsible for loading the jar packages under the extended directory (%java_home%/jre/lib/ext), allows users to package their developed classes into a jar package and place them in this directory to extend new functionality beyond the core class.

3. System Classloader\app ClassLoader: The class loader or the application class loader, is the jar package and classpath specified by the load CLASSPATH environment variable. In general, user-defined classes are loaded by app ClassLoader.


The relationships between the various ClassLoader: The parent-child relationship is reused in a combined relationship, noting that the parent-child relationship here is not implemented in an inheritance relationship.

Verify that the parent-child relationship between the class loader and the ClassLoader is public static void main (string[] args) throws exception{//gets the system/application ClassLoader ClassLoader Appclassloader = Classloader.getsystemclassloader (); SYSTEM.OUT.PRINTLN ("System/Application Class Loader:" + appclassloader);//Get the parent class loader of the system/application ClassLoader, get the extension classloader classloader Extcclassloader = Appclassloader.getparent (); System.out.println ("Extension class loader" + Extcclassloader); SYSTEM.OUT.PRINTLN ("Load path of extension class loader:" + system.getproperty ("Java.ext.dirs"));//Get the extension ClassLoader's parent loader, However, because the root classloader is not implemented in Java, you cannot get System.out.println ("extension class's parent ClassLoader:" + extcclassloader.getparent ());}}

the parent-delegate loading mechanism of the ClassLoader (emphasis): when a class receives a class load request, he first does not attempt to load the class himself, but instead delegates the request to the parent class, which is the case for each hierarchical classloader, so all load requests should be routed to the startup class to load, The subclass loader will attempt to load itself only if the parent loader has feedback that it cannot complete the request (the class it needs to load is not found under its loading path).


This process is shown in the marking process:




The source code implementation of the parent delegation model:

The main embodiment in the ClassLoader loadclass () method, the idea is simple: first check whether it has been loaded, if not loaded, call the parent class loader's LoadClass () method, If the parent loader is empty, the startup ClassLoader is used as the parent class loader by default. If the parent ClassLoader fails to load, the ClassNotFoundException exception is thrown, and its own Findclass () method is called to load.

< Span style= "font-size:18px" >

Public class<?> loadclass (String name) throws ClassNotFoundException {return LoadClass (name, false);  }protected synchronized class<?> loadclass (String name, Boolean resolve) throws ClassNotFoundException {//    First, check if the class has already been loaded class C = Findloadedclass (name);        if (c = = null) {try {if (parent! = null) {c = Parent.loadclass (name, false);        } else {c = findbootstrapclassornull (name);                }} catch (ClassNotFoundException e) {//ClassNotFoundException thrown if class not found From the Non-null parent class loader} if (c = = null) {//If still not found,            Then invoke Findclass in order/to find the class.        c = findclass (name);    }} if (resolve) {resolveclass (c); } return C;}


Here's a simple example of parental delegation Model code validation :

public class Classloadertest {public static void main (string[] args) {//Output Classloadertext class loader name System.out.println (" The name of the loader for the Classloadertext class: "+classloadertest.class.getclassloader (). GetClass (). GetName ()); System.out.println ("Name of the loader for the System class:" +system.class.getclassloader ()); System.out.println ("Name of the loader for the List class:" +list.class.getclassloader ()); ClassLoader cl = ClassLoaderTest.class.getClassLoader (); while (CL! = null) {System.out.print (Cl.getclass (). GetName () + CL = Cl.getparent ();} SYSTEM.OUT.PRINTLN (CL);}


The output is:


Explain:

1. The Classloadertest class is a user-defined class that is located under Classpath and loaded by the system/Application class loader.

2. both the System class and the list class belong to the Java core class, which is loaded by the Ancestor Class Launcher class loader, and the startup ClassLoader is implemented within the JVM through C + +, not Java, which naturally cannot inherit the ClassLoader class, and naturally cannot output its name.

3, while the arrow items represent the process of class loading, the hierarchy delegate, starting from the Ancestor class loader, is not loaded until the system/Application class loader .


So let's do a test, make the class into a jar package, copy it into the %java_home%/jre/lib/ext directory, run the Classloadertest class again .



Explain that, because the class's jar package is placed in the Extclassloader loading directory, after the root directory cannot find the corresponding class, the class load is completed at Extclassloader, and the appclassloader phase is ignored.


(continued, Next: Custom ClassLoader)






A detailed description of the JVM class loading mechanism (ii) class loader and parental delegation model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.