Schematic diagram of Java Virtual Machine 5. JVM Class Loader mechanism and class loading process

Source: Internet
Author: User

Schematic diagram of Java Virtual Machine 5. JVM Class Loader mechanism and class loading process
0. Preface

After reading this article, you will learn:

I. Why is the Jabalpur language cross-platform?

Ii. Analysis of startup and loading processes of Java virtual machines

Iii. What are the classloaders? What is its organizational structure?

4. What is the logic of the parent-parent load model and the underlying code implementation?

V. Class loaders and Classes Instance relationship

6. Thread context Loader

1. Why is Java cross-platform?

The reason why the Java language is cross-platform and can run on most operating system platforms is that the Java language runtime environment is in the Java Virtual Machine.
The Java Virtual Machine eliminates the differences between different platforms. As long as the Java Virtual Machine is installed on the operating system platform, everything developed using Java can run on it. As shown in:

Java Virtual Machine is essentially an executable program on each platform. For example, on the Windows platform, the Java Virtual Machine is just a java. EXE process.

Ii. Analysis of startup and loading processes of Java virtual machines

Next I will define a very simple java program and run it to gradually analyze the Startup Process of the java Virtual Machine.

 

package org.luanlouis.jvm.load;import sun.security.pkcs11.P11Util;/** * Created by louis on 2016/1/16. */public class Main{    public static void main(String[] args) {        System.out.println("Hello,World!");        ClassLoader loader = P11Util.class.getClassLoader();        System.out.println(loader);    }}
In the windows command line, enter:
Java org. luanlouis. jvm. load. Main
When you enter the preceding command:
Run the {JRE_HOME}/bin/java.exeprogram in windows. The java.exe program completes the following steps:
1. Apply for memory space of a specific size for the JVM according to the JVM memory configuration requirements;

2. Create a bootstrap loader instance and initially load the system class to the memory method area;

3. Create the JVM initiator instance Launcher and obtain the Class Loader ClassLoader;

4. Use the ClassLoader Instance obtained above to load the org. luanlouis. jvm. load. Main class we have defined;

5. When the load is complete, the JVM will execute the Main method entry of the main class and the Main method of the main class;

6. the java program is running and the JVM is destroyed.
Step 1. Apply for a specific size of memory space for the JVM according to the JVM memory Configuration Requirements

In order not to reduce the difficulty of understanding this article, I will not detail the JVM memory configuration requirements here. I will give a general introduction to the memory function division.

When a JVM is started, its memory consists of the following parts by function:

As shown in, JVM memory can be roughly divided Method Area)And Heap)And all the class definition information will be loaded Method Area.

For details about the content in the Method Area, refer to another blog:
Schematic diagram of Java Virtual Machine 3. JVM runtime data Zone

Step 2. Create a bootstrap loader instance and initially load the system class to the memory method area. After the JVM has applied for the memory space, the JVM will create Bootstrap Classloader)The bootstrap loader is implemented in the C ++ language and is responsible for loading the basic system-level classes required for running JVM virtual machines, such Java. lang. String, java. lang. ObjectAnd so on.

Bootstrap Classloader reads{JRE_HOME}/libAnd then load these system classes into the method area.

In this example, the bootstrap loader loads classes with {JRE_HOME}/lib. However, you can also use parameters-XbootclasspathOr System VariablesSun. boot. class. pathTo the specified directory to load the class.

Generally, {JRE_HOME}/lib stores the System Classes required for normal JVM operations, as shown in the following table:

File Name Description
Rt. jar The runtime environment package, rt is the runtime, and J2SE class definitions are all in this package.
Charsets. jar Character Set support package
Jce. jar Is a group of packages that provide a framework and implementation for encryption, key generation and negotiation, and the Message Authentication Code (MAC) algorithm.
Jsse. jar Secure Socket expansion package Java (TM) Secure Socket Extension
Classlist This file indicates the list of classes that the bootstrap loader should load.
Net. properties JVM network configuration information

Bootstrap ClassLoader)After the system class is loaded, the JVM memory will display the following pattern:

The bootstrap loader loads class information to the method area and organizes it in a specific way. For a specific class, it should have Runtime constant pool, Type information, Field Information, Method Information, Class Loader reference, Reference of the corresponding class instance. Class Loader referenceBecause these classes are loaded by the Bootstrap Classloader, And the Bootstrap Classloader is implemented in C ++, they cannot be accessed, therefore, the reference is NULL Reference of the corresponding class instance, After the Class loader puts the loaded Class information in the method area, a corresponding Class type instance will be created and placed in Heap, as the entry and entry point for class definition in the Method Area for developers to access.
Small test:
When we try to get the class loader of the system class such as java. lang. Object in the code, you will always get NULL:
        System.out.println(String.class.getClassLoader());//null        System.out.println(Object.class.getClassLoader());//null        System.out.println(Math.class.getClassLoader());//null        System.out.println(System.class.getClassLoader());//null
Step 3. Create the JVM initiator instance Launcher and obtain the Class Loader ClassLoader.

After the preceding steps are completed, the JVM basic runtime environment is ready. Next, let's get the JVM working: run the program org. luanlouis, jvm. load. Main we defined.

At this time, the JVM Virtual Machine calls the class already loaded in the Method AreaSun. misc. LauncherGetLauncher (), getSun. misc. LauncherInstance:

Sun. misc. launcher launcher = sun. misc. launcher. getLauncher (); // get the Java starter ClassLoader classLoader = launcher. getClassLoader (); // get the class Loader ClassLoader to load the class to the memory

 

Sun. misc. LauncherThe Singleton mode is used to ensure that only one JVM virtual machine exists.Sun. misc. LauncherInstance.
Inside the Launcher, it defines two class loaders (ClassLoader), which aresun.misc.Launcher.ExtClassLoaderAndsun.misc.Launcher.AppClassLoaderThese two class loaders are calledExtension ClassLoader)AndApplication ClassLoader). As shown in:

Legend note:All the Class loaders except Bootstrap Class Loader have the ability to determine whether a Class has been loaded by the Bootstrap Class Loader, you can directly return the corresponding Class Instance. If no instance exists, null is returned. The dotted line pointing to the bootstrap loader in the graph indicates the limited function to access the bootstrap loader.

At this timeLauncher. getClassLoader ()Method will returnAppClassLoaderInstance,AppClassLoaderSetExtClassLoaderAs your parent loader.

WhenAppClassLoaderWhen a class is loaded, the parent loader is first attemptedExtClassLoaderIf the parent LoaderExtClassLoaderIf the load is successfulAppClassLoaderReturns the parent loader directly.ExtClassLoaderLoading result; if the parent LoaderExtClassLoaderLoading failed,AppClassLoaderIt will determine whether the class is a guided system class (that is, whether it is loaded through the Bootstrap class loader, which will call the Native Method for search); if the class to be loaded is not a system boot class, then, the ClassLoader will try to load it by itself. If the load fails, "ClassNotFoundException" will be thrown ".

The specific workflow of AppClassLoader is as follows:

Parent-delegation model ):
The loading class mode of the application Class Loader AppClassLoader discussed above is the parent-delegation model we often call ).
For a specific class loader, you should specify a parent class loader for it. When using it to load the class:
1. Entrust the parent class loader to help with loading;
2. If the parent class loader cannot be loaded, check whether the class has been loaded by the bootstrap class loader;
3. If the class has not been loaded by the bootstrap loader, the current class loader should load the class by itself;
4. If the load is successful, the corresponding Class is returned. Object. If it fails, an exception "ClassNotFoundException" is thrown ".
Note:
In the Parent-Child delegation model, "Parent-Child" does not mean that it has two parent class loaders. A Class Loader should only have one parent loader. In the preceding steps, there are two roles:
1. parent classloader: it can be used to load classes for the subloader.
2. bootstrap classloader: The subclass loader can only determine whether a class is Bootstrap loaderLoaded, but cannot delegate it to load a class. In other words, the subclass loader cannot access the bootstrap loader. The bootstrap loader is transparent to other classloaders.

Generally, the dual-parent load model is as follows:


  Step 4. Use the ClassLoader to load the Main class

You can use the launcher. getClassLoader () method to return the AppClassLoader instance. Then, it is time for the AppClassLoader to load the org. luanlouis. jvm. load. Main class.

ClassLoader classloader = launcher. getClassLoader (); // obtain the AppClassLoader class classLoader. loadClass ("org. luanlouis. jvm. load. Main"); // load the custom class

Org. luanlouis. jvm. load. the Main class is compiled into org. luanlouis. jvm. load. main class binary file. This class file contains a Constant Pool struct to store the class's bright information. A constant of the CONSTANT_CLASS_INFO type exists in the constant pool, indicating the classes to be used in the class:

When AppClassLoader needs to load org. luanlouis. jvm. load. when the Main class is used, it will view the definition of the class and find that it uses the other class: sun. security. pkcs11.P11Util, java. lang. object, java. lang. system, java. io. printStream, java. lang. class; org. luanlouis. jvm. load. to run the Main class normally, you must first ensure that the classes declared in the Main class are successfully loaded. Therefore, the AppClassLoader must first load these classes into the memory. (Note: For ease of understanding, there is no need to consider lazy loading. In fact, the JVM loading process is much more complicated than this)

Loading sequence:

1. Load java. lang. Object, java. lang. System, java. io. PrintStream, java, lang. Class

When the AppClassLoader tries to load these classes, it will first delegate ExtClassLoader to load; while ExtClassLoader finds that it does not have its loading range and returns null; AppClassLoader finds that the parent class loader ExtClassLoader cannot load, the system checks whether these classes have been loaded by BootstrapClassLoader. The result shows that these classes have been loaded by BootstrapClassLoader, and the corresponding Class is directly returned without repeated loading. Instance;

2. Load sun. security. pkcs11.P11Util

This is in the {JRE_HOME}/lib/ext/sunpkcs11.jar package and belongs to the scope where ExtClassLoader is responsible for loading. When the AppClassLoader tries to load these classes, it will first delegate ExtClassLoader to load; while ExtClassLoader finds that it is within the loading range, so ExtClassLoader is responsible for loading it into the memory. ExtClassLoader is loading sun. security. when pkcs11.P11Util is used, it also analyzes the classes used in this class, and loads these classes into the memory before loading sun. security. pkcs11.P11Util. After loading successfully, the corresponding Class is directly returned. Instance;

3. load org. luanlouis. jvm. load. Main

When the AppClassLoader tries to load these classes, it will first delegate ExtClassLoader to load; while ExtClassLoader finds that it does not have its loading range and returns null; AppClassLoader finds that the parent class loader ExtClassLoader cannot load, the system checks whether these classes have been loaded by BootstrapClassLoader. The result shows that the BootstrapClassLoader has not loaded it. At this time, the AppClassLoader can only load it into the memory, and then return the corresponding Class Instance reference;

ClassLoader is returned only when all the preceding three steps are successful. loadClass ("org. luanlouis. jvm. load. main "). After the above operations are completed, the JVM memory method area will look like this:

As shown in:

The class information area of the JVM method area is divided by class loaders. Each Class Loader maintains its own class information. When a Class Loader loads a class, creates a corresponding Class in the JVM memory Heap. Indicates the entry to access this type of information.
Step 5. Use the Main method of the main class as the program entry to run the program

 

Step 6. After the method is executed, the JVM destroys and releases the memory.

 

Iii. What are the classloaders? What is its organizational structure?

Class Loader: a tool that can load classes, as its name implies. JVM defines three Class loaders: Bootstrap Class Loader, Extension Class Loader, and Application Class Loader ). Of course, we sometimes define some class loaders to meet our own needs.

Bootstrap Class Loader: This Loader enables JVM to use the C/C ++ underlying code to load the System Classes required for JVM runtime, these System classes are in the {JRE_HOME}/lib directory.Because the class loader is implemented using the underlying C/C ++ language related to the platform, the loader cannot be accessed by Java code. However, we can check whether a class has been loaded by the bootstrap loader.We often use system classes such as java. lang. string, java. lang. object, java. lang *....... these are all stored in {JRE_HOME}/lib/rt. in the jar package, when the JVM system is started, the bootstrap loader will load it into the JVM memory method area.

Extension Class Loader: This Loader is an Extension Class used to load java. The Extension Class is usually stored in the {JRE_HOME}/lib/ext/directory, it is used to provide additional functions besides the system class.The extension class loader is the top class loader that can be accessed by Java code of the entire JVM loader, that is, the super parent loader. The extension class loader does not have the parent class loader.

Applocatoin Class Loader: This Loader is used to load user code and is the entry to user code. I often run the command java xxx. x. xxx. x. x. XClass. In fact, JVM is used to load xxx. x. xxx. x. XClass. The application Class Loader regards the extension class loader as its parent class loader. when it tries to load the class, it first tries to let its parent loader-extension class loader load; if the extension Class loader is loaded successfully, the Class loading result is returned directly. If the instance fails to be loaded, the system will ask if the bootstrap loader has loaded the class. Only when the class loader is not loaded will the Application Loader try to load it by itself. Because Xxx. x. xxx. x. x. XClassIs the entry to the entire user code. In Java Virtual Machine specifications, it is called the Initial Class ).


Custom Class Loader: You can customize a Class Loader to load classes. All class loaders must inherit the java. lang. ClassLoader class.

4. What is the logic of the parent-parent load model and the underlying code implementation? The above is an example of what a dual-parent load model is and what its mechanism is. These things can be viewed through the underlying code.

We can also view the implementation of the core method loadClass () of java. lang. ClassLoader through the JDK source code:

// Provide the binary name of the class. If the Class is loaded successfully, the returned value indicates the class corresponding to the class.
  
   
Instance public Class
   LoadClass (String name) throws ClassNotFoundException {return loadClass (name, false);} protected Class
   LoadClass (String name, boolean resolve) throws ClassNotFoundException {synchronized (getClassLoadingLock (name) {// first, check whether it has been recorded by the current class loader, if it has been loaded, the corresponding Class is directly returned.
   
    
Instance Class
    C = findLoadedClass (name); // first load if (c = null) {long t0 = System. nanoTime (); try {if (parent! = Null) {// if there is a parent class loader, let the parent class loader load c = parent. loadClass (name, false);} else {// if no parent loader exists, check whether the loader has been loaded. If yes, return c = findBootstrapClassOrNull (name );}} catch (ClassNotFoundException e) {// ClassNotFoundException thrown if class not found // from the non-null parent class loader} // the parent loader fails to load, if the loader is not loaded by the bootstrap loader, try to load If (c = null) {// if still not found, then invoke findClass in order // to find the class. long t1 = System. nanoTime (); // try to load c = findClass (name); // this is the defining class loader; record the stats sun. misc. perfCounter. getParentDelegationTime (). addTime (t1-t0); sun. misc. perfCounter. getFindClassTime (). addElapsedTimeFrom (t1); sun. misc. perfCounter. getFindClasses (). increment () ;}}// whether to parse the class if (resolve) {resolveClass (c) ;}return c ;}}
   
  

Correspondingly, we can sort out the workflow of the parent-child model:

I believe that after reading this figure, the reader will have a very clear context for the model loaded by both parents. Of course, this is the default behavior of JDK to load classes. We can inherit and rewrite this method to change its behavior.

V. Class loaders and Classes Instance relationship

6. Thread context Loader

The execution of any piece of Java code has a corresponding thread context. If we want to see which thread is executing the current code in the code, we often use the following method:

Thread thread = Thread. currentThread (); // returns a reference to the current running Thread

Correspondingly, we can specify a class loader for the current thread. In the preceding exampleJava org. luanlouis. jvm. load. MainWhen an application class loader is created, the JVM will create a Main thread, and when the application class loader is created, AppClassLoader will be set to the context class loader of the Main thread:

Public Launcher () {Launcher. extClassLoader var1; try {var1 = Launcher. extClassLoader. getExtClassLoader ();} catch (IOException var10) {throw new InternalError ("cocould not create extension class loader", var10);} try {this. loader = Launcher. appClassLoader. getAppClassLoader (var1);} catch (IOException var9) {throw new InternalError ("cocould not create application class loader", var9 );} // set AppClassLoader to the context loader Thread of the current Thread. currentThread (). setContextClassLoader (this. loader );//.......}

The thread context class loader looks at the class loading from the thread's perspective. It binds a class loader to each thread and can free up the class Loading Model from the pure dual-parent Loading Model, to meet specific loading requirements.

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.