Java class Loader

Source: Internet
Author: User

1 Basic information

Each developer is certainly not unfamiliar with the Java.lang.ClassNotFoundExcetpion exception, which involves class loading in the Java technology architecture. Java's class loading mechanism is the core of the technical system, although not much directly with the majority of developers, but the mechanism behind it has a certain understanding to help troubleshoot the application of class loading failure and other technical issues, to understand the Java Virtual Machine Connection model and Java language Dynamics are very helpful.

2 Java Virtual Machine class loader structure brief

2.1 JVM Three pre-defined type ClassLoader

Let's first look at the three types of class loaders that are predefined by the JVM, and when a JVM starts, Java defaults to using the following three types of class loaders:

Startup (Bootstrap) ClassLoader : The Boot class loader is a class loader implemented with native code that is responsible for <java_runtime_home>/ The Kernel class library or the-xbootclasspath option specified in Lib below is loaded into memory by the jar package. because the boot ClassLoader involves the virtual machine local implementation details, the developer cannot directly get a reference to the startup ClassLoader, so it is not allowed to operate directly from the reference.

Extension (Extension) class loader : The extension ClassLoader is implemented by Sun's Extclassloader (Sun.misc.launcher$extclassloader). It is responsible for loading the < Java_runtime_home >/lib/ext or the class library in the specified location-djava.ext.dir the system variable into memory. Developers can use the standard extension class loader directly.

System Class Loader : The system ClassLoader is implemented by Sun's Appclassloader (Sun.misc.launcher$appclassloader). It is responsible for loading the class libraries in the directory under the system classpath Java-classpath or-djava.class.path variables into memory. Developers can use the System class loader directly.

In addition to the three types of loaders listed above, there is a special type of thread-context ClassLoader , which is described separately later.

Introduction and analysis of 2.2-class loaded parental delegation mechanism

Here, it should be emphasized that the JVM defaults to the parent delegation mechanism when loading the class. In layman's words, when a particular class loader receives a request to load a class, it first delegates the load task to the parent class loader, recursively, and returns if the parent ClassLoader can complete the class load task, only to load itself when the parent ClassLoader cannot complete the load task. with regard to the virtual machine's default parental delegation mechanism, we can make simple analysis from the system ClassLoader and the extended class loader as an example.

Figure one standard extension class loader inheritance hierarchy diagram

Figure two System class loader inheritance hierarchy diagram

We can see from diagram one and figure two that the ClassLoader are inherited from the Java.lang.ClassLoader abstract class. Let's take a look at a few of the most important methods of java.lang.ClassLoader in this article:

1 //loads the binary type of the specified name (including the package name) for the user to invoke the interface2  PublicClass<?> loadclass (String name)throwsclassnotfoundexception{...} 3   4 //loads the binary type of the specified name (including the package name) and specifies whether to parse it (but the resolve parameter here does not necessarily really achieve the effect of parsing) for inheritance5 protected synchronizedClass<?> loadclass (String name,BooleanResolvethrowsclassnotfoundexception{...} 6   7 //The Findclass method is typically called by the LoadClass method to load the specified name class for inheritance8 protectedClass<?> Findclass (String name)throwsclassnotfoundexception {...} 9   Ten //defines a type that is typically called after the corresponding bytecode is read in the Findclass method, and can be seen as non-inheritable One //(Note: The JVM has implemented the corresponding specific functions, parsing the corresponding bytecode, resulting in the corresponding internal data structure to the method area, so there is no need to overwrite, directly call on it) A protected FinalClass<?> defineclass (String name,byte[] B,intOffintLenthrowsClassformaterror{...}

By further analyzing the standard extension class loader (sun.misc.launcher$extclassloader) and the system ClassLoader (Sun.misc.launcher$appclassloader Code, and the code of its common parent (Java.net.URLClassLoader and Java.security.SecureClassLoader) can be seen, none of them overwrite The default load delegation rule in Java.lang.ClassLoader---loadclass (... ) method. in this case, we can parse the code of the LoadClass (String name) method in Java.lang.ClassLoader to analyze what the parent delegation mechanism of the virtual machine will look like by default:

1  PublicClass<?> loadclass (String name)throwsClassNotFoundException {2     returnLoadClass (Name,false); 3 }  4   5 protected synchronizedClass<?> loadclass (String name,Booleanresolve)6         throwsClassNotFoundException {7   8     //first determine if the type has been loaded9Class C =Findloadedclass (name); Ten     if(c = =NULL) {   One         //if it is not loaded, it is delegated to the parent class to load or delegate to the startup class loader to load A         Try {   -             if(Parent! =NULL) {   -                 //If there is a parent ClassLoader, delegate to the parent ClassLoader to load thec = Parent.loadclass (name,false);  -}Else {   -                 //If the parent ClassLoader does not exist, check to see if the class is loaded by the Startup class loader. -                 //by calling the local method native FindBootstrapClass0 (String name) +c =FINDBOOTSTRAPCLASS0 (name);  -             }   +}Catch(ClassNotFoundException e) { A             //If neither the parent ClassLoader nor the startup ClassLoader can complete the load task, the load function is called itself atc =Findclass (name);  -         }   -     }   -     if(resolve) { - Resolveclass (c);  -     }   in     returnC;  -}

With the above code analysis, we can have a more perceptual understanding of the Parental delegation class loading mechanism adopted by the JVM, and then we will analyze the relationship between the Startup class loader, the standard extension classloader, and the system ClassLoader. You may have seen a picture like this from a variety of sources:


Figure three-Class loader default delegation diagram

The image gives a visual impression of the system ClassLoader is the parent class loader is the standard extension class loader, the standard extension ClassLoader is the parent class loader is the launch ClassLoader, the following we use code specific test:

1  Public classLoadertest {2   3      Public Static voidMain (string[] args) {4         Try {  5 System.out.println (Classloader.getsystemclassloader ()); 6 System.out.println (Classloader.getsystemclassloader (). GetParent ()); 7 System.out.println (Classloader.getsystemclassloader (). GetParent (). GetParent ()); 8}Catch(Exception e) {9 E.printstacktrace (); Ten         }   One     }   A}

Description: The system ClassLoader can be obtained directly through Java.lang.ClassLoader.getSystemClassLoader ().
The code output is as follows:

1 [email protected] 2 [email protected]0dea4e 3 null

With the above code output, we can determine that the system ClassLoader's parent loader is the standard extension classloader, but when we try to get the parent classloader of the standard extension classloader, we get null, that is, the standard extension ClassLoader itself enforces the setting of the parent ClassLoader as null . we're still using the code to analyze it.

Let's take a look at the two constructors that are implemented by default in the Java.lang.ClassLoader abstract class:

protectedClassLoader () {SecurityManager security=System.getsecuritymanager (); if(Security! =NULL) {security.checkcreateclassloader (); }      //by default, the parent class loader is set to the system ClassLoader, Getsystemclassloader () gets the system class loader     This. Parent =Getsystemclassloader (); Initialized=true; }    protectedClassLoader (ClassLoader parent) {SecurityManager Security=System.getsecuritymanager (); if(Security! =NULL) {security.checkcreateclassloader (); }      //force the parent class loader to be set     This. Parent =parent; Initialized=true; }  

When declared as a private variable, there is no public or protected set interface (corresponding setter method) available for access by the derived class, and with the output of the preceding test code, we can infer:
1. The System ClassLoader (Appclassloader) calls the ClassLoader (ClassLoader parent) constructor to set the parent ClassLoader to the standard Extension class loader (Extclassloader). (Because if you do not force the setting, the default is to get and set the system ClassLoader by calling the Getsystemclassloader () method, which obviously does not match the results of the test output.) )
2. The Extension class loader (Extclassloader) calls the ClassLoader (ClassLoader parent) constructor to set the parent ClassLoader to NULL. (Because if you do not force the setting, the default is to get and set the system ClassLoader by calling the Getsystemclassloader () method, which obviously does not match the results of the test output.) )
Now we may have the doubt that the Extension class loader (Extclassloader) 's parent ClassLoader is forced to null, so why does the extended ClassLoader delegate the load task to the Startup class loader?

Figure Four Standard extension class loader and system ClassLoader member outline view


Figure V Extension class loader and system ClassLoader Public parent class Member outline view

As can be seen in Figure four and figure V, the standard extension ClassLoader and the System class loader and its parent class (java.net. URLClassLoader and Java.security.SecureClassLoader) did not overwrite the default load delegation rule in Java.lang.ClassLoader---loadclass (... Method The default Load delegation rule in Java.lang.ClassLoader has been parsed before, and if the parent loader is null, the local method is called to start the class load attempt. So, in figure three, the delegation relationship between the start class loader, the standard extension classloader, and the system ClassLoader is in fact still true. (in the later section of the user-defined ClassLoader, more in-depth analysis is also done).

Java class Loader

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.