In-depth Java Virtual machine loaders

Source: Internet
Author: User
Tags thread class

Objective:
The virtual machine design team puts the class in the load phase " get a binary byte stream that describes this class by naming the permissions of a class"This action is implemented on the outside of the virtual machine, letting the program decide for itself how to get the required classes." The code module that implements this action is called class Loader

It was originally developed to meet the needs of Java applets, but now the Java applet has largely declared death, but the ClassLoader has been brilliantly in the areas of class hierarchy, OSGi, hot deployment, code encryption, and so on. It is an important cornerstone in the Java technology architecture.

for any class, it is necessary to establish the uniqueness of the virtual machine with the loader that loads the class and the class itself. Popular say is: Compare two classes are equal, these two classes must be the same class loader premise to make sense. Otherwise, even if two classes are sourced from the same class file, the two classes must be unequal as long as the loader is different.

Note:
The "equality" mentioned here includes the following: The Equals method of the class object, the Isassignableform method, the return result of the Isinstance method, and the decision of the relationship between the object and the instanceof keyword.

Parental delegation Model

In the virtual machine perspective, there are only two classes of ClassLoader: Start the ClassLoader and other ClassLoader. The startup ClassLoader is part of the virtual machine and is implemented in C + +, while the other ClassLoader is implemented in Java. In the eyes of developers, the ClassLoader can be more nuanced:
To start the class loader:
This class loader is responsible for loading the class libraries that are placed in the Java_home\lib directory, or in the path specified by the-xbootclasspath parameter, into the virtual machine. The startup ClassLoader cannot be referenced directly by a Java program.

Extension class Loader:
It is responsible for all class libraries that are in the Java_home\lib\ext directory or are specified by the Java.ext.dirs system variable, and developers can use the extension classloader directly.

Application class Loader:
This class loader is made up of Sun,misc. Implemented by Launcher$appclassloader. Because this classloader is the return value of the Getsystemclassloader () method in ClassLoader, it is generally referred to as the System class loader. It is responsible for loading the class library specified on the User class path (ClassPath). Developers can use this class loader directly. If the application does not have its own classloader, this is the default class loader in the program.

Note:
All of our applications are loaded with these three kinds of loaders, and if necessary, you can also add your own classloader. The relationship between the class loader and the custom class loader is as follows:

The parental delegation model stipulates that each classloader (except the startup ClassLoader) must have a parent class, and that the relationship is not an inheritance implementation, but is implemented by a combination, and requires that when the current ClassLoader is called, the parent class must be loaded, and if there is no parent class, it is given to the startup ClassLoader to load, If the parent class returns cannot be loaded, the current class loader is loaded, and if it is not currently loaded, ClassNotFoundException is thrown.

The benefit of this is that there is a priority to ensure that a class is only loaded by a classloader such as a virtual machine, and if it is a priority, then it is possible that the same class is loaded multiple times in the virtual machine by different classloader, and that the classes are not equal.

The

Parent-delegated code is in Java.lang.ClassLoader's LoadClass method, and we can tell by analyzing the source code:

/** * Loads The class with the specified <a href= "#name" >binary name</a>.     The * default implementation of this method searches for classes in the * following order: * * <ol> * * <li><p> Invoke {@link #findLoadedClass (String)} to check if the class * has already been l  Oaded. </p></li> * * <li><p> Invoke the {@link #loadClass (String) <tt>loadclass</tt&gt ;}  Method * on the parent class loader.  If The parent is <tt>null</tt> the class * Loader built-in to the Vsan is used, instead. </p></li> * * <li><p> Invoke the {@link #findClass (String)} method to find the * C  Lass.     </p></li> * * </ol> * <p> If The class was found using the above steps, and the * <tt>resolve</tt> flag is true, this method would then invoke the {@link * #resolveClass (Class)} mEthod on the resulting <tt>Class</tt> object. * * <p> subclasses of <tt>ClassLoader</tt> is encouraged to override {@link * #findClass (String  )}, rather than this method. </p> * * <p> Unless overridden, this method synchronizes on the result of * {@link #getClassLoadin     GLock <tt>getclassloadinglock</tt>} method * During the entire class loading process. * * @param name * The <a href= "#name" >binary name</a> of the class * * @param resolv E * If <tt>true</tt> then resolve the class * * @return the resulting <tt>Class< /tt> Object * * @throws classnotfoundexception * If The class could not be found */Protec Ted Class<?> LoadClass (String name, Boolean resolve) throws ClassNotFoundException {synchronized ( Getclassloadinglock (name)) {//First, check if the class HAs already been loaded class<?> C = findloadedclass (name);                if (c = = null) {Long T0 = System.nanotime ();                    try {if (parent! = null) {c = Parent.loadclass (name, false);                    } else {c = findbootstrapclassornull (name); }} catch (ClassNotFoundException e) {//ClassNotFoundException thrown if class not Fou                    nd//From the Non-null parent class loader} if (c = = null) {                    If still not found, then invoke Findclass in order//to find the class.                    Long T1 = System.nanotime ();                    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 ();            }} if (resolve) {resolveclass (c);        } return C; }    }

Destroying parental delegation models
The parental delegation model is not a mandatory constraint model, but a class loader implementation that Java designers recommend to developers. Most of them follow this model. But by the time the author of the Java Virtual machine has written this book, it has been destroyed three times.

First time:
Occurs before the parent delegation model, because the parent delegation model is introduced after jdk1.2. The class loader and abstract class Java.lang.ClassLoader appear as early as jdk1.0. To be compatible with the ClassLoader before the parent delegation model, the Java design team had to compromise, A protected Findclass method was added to the Java.lang.ClassLoader class after jdk1.2, before which the user inherits Java.lang.ClassLoader in order to rewrite the LoadClass () method , because the virtual machine invokes a private method Loadclassinternal () of the ClassLoader when the class is loaded, and the only logic of this method is to call its own loadclass () method. In front of the loadclass source, we can know that if the parent class fails to load, the class loading process defined by the Findclass () method is called. This guarantees that the parent delegation model can be satisfied.

Second time:
The second is due to the shortcomings of the parent model itself, although the parent delegation model solves the unity of the basic classes of each classloader well, but what if the base class calls back the user's code again? For example: Jdni service, Jdni service is the standard Java services, its code is loaded with the launcher loader, but the purpose of Jdni is to centrally manage and find resources, It needs to invoke the code of the Jdni interface provider implemented by other independent vendors and deployed under the classpath of the application, but the startup class does not recognize the code. To solve these problems, the Java design team provides an elegant design: the thread context ClassLoader. This classloader can be set by the Setcontextclassloader () method of the Java.lang.Thread class, if it is not set when the thread is created, it inherits one from the parent thread, if the application is not set globally, Then this classloader is the application class loader.

The Jdni service uses this thread context loader to load the required SPI code, which is where the parent ClassLoader requests the subclass loader to complete the class load action. In Java, the design of the SPI load action is basically this way, such as: Jdni, JDBC, JAXB, JCE and Jbi.

Third time:
The third time is due to the user's pursuit of the dynamic nature of the program, the dynamic is said to mean: Code hot swap, Module heat deployment, and so on, it is hoped that the application can be like computer peripherals, plug the mouse, keyboard, do not restart the machine. The temptation for a hot deployment to an enterprise's production environment is beyond doubt.

In-depth Java Virtual machine loaders

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.