Java class Loader (i)-class loader hierarchy and model

Source: Internet
Author: User
Tags thread class

Class Loader

?? The virtual machine design team takes the "fully qualified name of a class to obtain a description of this type of binary byte stream" in the class loading phase, which is implemented outside the Java Virtual machine. So that the application can decide for itself how to get the classes it needs. The code module that implements this action is called the class loader.

class loader hierarchy (level)

?? From the JVM's point of view, there are only two different class-loader types.
?? The first class is the Startup class loader (Bootstrap ClassLoader): This class loader is primarily loaded into the classes that the JVM itself needs to work on. This class loader is implemented in the C + + language (specifically, hotspot). is part of the virtual machine itself.

Responsible for storing in the%java_home%\lib folder, or in the path specified by the-xbootclasspath parameter. and is recognized by the virtual machine (only according to the file name. such as Rt.jar, class libraries whose names do not conform are loaded into the virtual machine memory even if they are placed in the Lib folder.
?? There is also a class of all other type loaders, which are implemented by Java and are independent of the virtual machine.


?? Extension ClassLoader: This class is implemented in its Sun.misc.Launcher$Extclassloader, which is responsible for loading the%java_home%\lib\ext folder, or the entire class library in the path specified by the JAVA.EXT.DIRS system variable, the developer is able to use the extension class loader directly.


?? Application ClassLoader: This class loader is implemented by Sun.misc.Launcher$appclassloader. Because this class loader is the return value of the Getsystemclassloader () method in ClassLoader, it is generally used as the System class loader. It is responsible for loading the class library specified on the user classpath, which the developer can use directly with the class loader. Suppose the application does not have its own class loader defined by itself. In normal circumstances this is the default class loader in the program.


?? The parent of Appclassloader is Extclassloader.

Very many articles in the introduction of the structure of the ClassLoader hierarchy, Bootstrap ClassLoader is also listed in the upper level of Extclassloader. In fact Bootstrap ClassLoader does not belong to the class hierarchy of the JVM. Because Bootstrap ClassLoader did not comply with the classloader of the carrier shares. In addition Bootstrap ClassLoader no subclass, Extclassloader's parent class is not bootstrap classloader,extclassloader and there is no parent class, The top-level parent class that we can extract in the application is Extclassloader.
code example:

        ClassLoader cl = Thread.currentThread().getContextClassLoader();        System.out.println(cl.toString());        System.out.println(cl.getParent());        System.out.println(cl.getParent().getParent());

?? Output Result:

sun.misc.Launcher$AppClassLoader@7dd74c03sun.misc.Launcher$ExtClassLoader@41bf9980null
How to get ClassLoader
    1. This.getclass (). getClassLoader ();//Use the ClassLoader of the current class
    2. Thread.CurrentThread (). Getcontextclassloader ();//Use the ClassLoader of the current thread
    3. Classloader.getsystemclassloader ();//Use System ClassLoader

?? code example:

    public void test()    {        System.out.println(this.getClass().getClassLoader().toString());        System.out.println(Thread.currentThread().getContextClassLoader());        System.out.println(ClassLoader.getSystemClassLoader());    }

?? Output:

sun.misc.Launcher$AppClassLoader@41bf9980sun.misc.Launcher$AppClassLoader@41bf9980sun.misc.Launcher$AppClassLoader@41bf9980

[Tips] How to obtain class properties for classes:
1. Class.forName (full classpath);
2. This.getclass ();
3. Use. class, for example String.class
4. For basic data types: Class C1 = Int.class (class is just a contract tag.) Not a member property) or class C2 = Integer.type

?? There are two ways in which the JVM loads class files into memory:
?? 1. Implicit loading: The so-called implicit loading is not to record the required classes by invoking ClassLoader in the code. Instead, it uses the JVM to proactively load the required class-to-memory way.

For example, when we integrate or reference a class in a class, the JVM finds that the referenced class is not in memory when it parses the current class, and then voluntarily loads the classes into memory.
?? 2. Display loading: The opposite display loading is the way we load a class in code by calling the ClassLoader class, for example, calling This.getClass.getClassLoader (). LoadClass () or Class.forName ()。 or our own implementation of the ClassLoader Findclass () method and so on.

Parental delegation Model

?? The parental delegation model requires livestock Dingcheng's startup class loader (Bootstrap ClassLoader). The rest of the class loader should have its own parent class loader. the parent-child relationship between the class loader is generally not implemented in the inheritance relationship, but rather is the code that uses the combined composition relationship to reuse the parented loader .


?? The parental delegation model is not a mandatory constraint model, but rather a class loader implementation that Java designers recommend to developers. Most of the class loader in the Java world follows this model, but there are exceptions. Until now. The parent delegation model has 3 of this larger "destroyed" situation, which is explained later.


?? The parent delegation model works by assuming that a class loader receives a class-loaded request, which first does not attempt to load the class itself, but instead delegates the request to the parent-class loader, which is the case for each level of the class loader. So all loading requests should finally be routed to the top-level startup class loader. The child loader tries to load itself only if the parent loader feedback itself cannot complete the load request (it does not find the desired class in the search scope).
?? The role of the parental trust mechanism is to prevent the system jar package from being replaced locally, because the lookup method process starts at the bottom of the search. Therefore, the classloader that we define in general need to use such a mechanism, We just have to inherit java.lang.ClassLoader to achieve findclass, assuming that a lot of other controls are needed, and that the classloader of your own definition needs to rewrite the LoadClass method, which is more complicated than the tomcat loading process. Be able to view relevant information through other documentation.
?? The parental delegation model is important to ensure the stable operation of the Java program, which is now java.lang.ClassLoader in the LoadClass () method. For example, the following:

protected Class<?

> LoadClass (String name, Boolean resolve) throws ClassNotFoundException {synchronized (Getclassloadin GLock (name)) {//First, checkifThe 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 thrownif class not found //From the non-NULLParent class loader }if(c = =NULL) {//If still notFound ThenInvoke FindclassinchOrder//To find the class.Long T1 = System.nanotime (); c = findclass (name);// This isThe 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); }returnC } }

?? The loading steps of the LoadClass () method are:
?? 1. Call Class C = Findloadedclass (name) to check if the class has been loaded;
?? 2. Call the LoadClass method on the parent class loader:
??? c = Parent.loadclass (name, false);
?? Assuming that the parent class loader is null, use the virtual machine's built-in class loader:
??? c = findbootstrapclassornull (name);
?? 3. When the parent loader fails to load, call its own Findclass method to load the class:
??? c = findclass (name);

The process of loading class into each ClassLoader is:
1. Check if this class has been loaded (that is, if there is a class in the cache), false to 8, assuming no to 2;
2. Assume that the parent ClassLoader does not exist (no parent.) That the parent must have been bootstrap ClassLoader), to 4;
3. Request that the parent ClassLoader be loaded. Assuming success to 8, unsuccessful to 5;
4. Request that the JVM be loaded from bootstrap ClassLoader. Assuming success to 8;
5. Look for the class file (from the classpath associated with this classloader). If not found then to 7;
6. Load class from the file. to 8;
7. Throw classnotfoundexception;
8. Return to class.

Destroying parental delegation models

?? As mentioned above, there have been 3 large "broken" cases of parental delegation models, which are described in detail here.
?? First time.

Occurs before the parent delegation model appears (before jdk1.2 is published). Because the parent delegation model is not introduced until after jdk1.2. The class loader and abstract class Java.lang.ClassLoader have existed in the jdk1.0 era, and in the face of existing user-defined class loader implementation code, Java designers have to make some compromises when introducing parental delegation models.

History has become the past, detailed here not to repeat. It is important to note that the user is not encouraged to overwrite the LoadClass () method after jdk1.2, but that their classes should be loaded into logic findclass () so that the rules of the parent delegation model are guaranteed.
?? The second time.

Due to the defects of the model itself, the parent delegation model overcomes the unity problem of the basic classes of each class loader very well. When the parent loader needs to request a subclass loader to complete the class load action, for example the Jndi service: its code is loaded by the Startup class loader. However, the purpose of Jndi is to centrally manage and locate resources. It needs to invoke the code of the Jndi provider (SPI) implemented by the standalone vendor and deployed under the application's classpath, but the startup class loader does not "recognize" the code.

This is going to use the thread context loader (thread contextual ClassLoader). This class loader can be set by the Setcontextclassloader () method of the Java.lang.Thread class.
?? How does this come out again a context ClassLoader? What's the use of it? We are able to specify a suitable classloader as the context ClassLoader of this thread when this thread is executed by using the Setcontextclassloader method for the thread thread. We can use the Getcontextclassloader method to get this context ClassLoader, and it can be used to load the class we need.

The default is System ClassLoader. Using this feature, we can "break" the ClassLoader trust mechanism. The parent ClassLoader can obtain the context ClassLoader of the current thread. And this context ClassLoader can be its son classloader or other ClassLoader, then the parent ClassLoader can obtain the required Class from it, This breaks the limit that can only be requested by the parent ClassLoader. This mechanism satisfies the class that is loaded by the system ClassLoader (that is, in the JVM classpath) when our classpath is determined at execution time and is loaded by a custom classloader, through the context ClassLoader obtains custom ClassLoader and loads into a specific class (typically abstract classes and interfaces, which are in fact present in custom ClassLoader), such as a servlet in a Web application that is loaded with such a mechanism.
?? Third time.

Because of the user's pursuit of the dynamics of the program, which is referred to as "dynamic" refers to the current some very "hot" Name: Code hot swap, module thermal deployment, similar to the mouse keyboard hot plug.

Detailed to see OSGi. In an OSGi environment. The class loader is no longer a tree structure in the parent delegation model, but a mesh structure. Can read some relevant information in detail.

Java class Loader (i)-class loader hierarchy and model

Related Article

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.