Java class loader Architecture

Source: Internet
Author: User

JVM classloader Architecture:

A, bootstrap classloader/start class loader
It is mainly responsible for packaging the core API under the jdk_home/lib directory or the jar specified by the-xbootclasspath option.

B. Extension classloader/extension class loader
It is mainly responsible for packaging the jar package in the jdk_home/lib/EXT directory or the jar package in the directory specified by-djava. Ext. dirs.

C, system classloader/system Class Loader
It is mainly responsible for packaging classes and jar files in the directory referred to by Java-classpath/-djava. Class. Path.

B. User custom classloader/user-defined class loader (subclass of Java. Lang. classloader)
During the program running, the class file is dynamically loaded using the subclass of Java. Lang. classloader, reflecting the Dynamic Real-time class loading feature of Java.

Classloader features:

1. Each classloader maintains its own namespace. Two classes with the same name cannot appear in the same namespace.
2. To implement the Class Loader security mechanism at the top layer of the Java Security Sandbox Model, Java adopts the "parent-parent delegated load chain" structure by default.
For example:

In the class diagram, bootstrapclassloader is a separate Java class. In fact, it should not be called a Java class here.
Because it does not need Java implementation at all.

It is constructed at JVM startup and is responsible for the core library of the Java platform. (As described above)

Start the class loading implementation (in fact, we don't need to care about this, but if you are interested, you can study it ):
Bootstrap classloader class loading Principle Exploration

To load a class, follow these steps:

Classloader class loading logic analysis. The following logic is the classloader loading process except bootstrapclassloader:

// Check whether the class has been loaded Class C = findloadedclass (name); If (C = NULL) {// the specified class has not been loaded try {If (parent! = NULL) {// if the parent class loader is not empty, delegate to the parent class to load c = parent. loadclass (name, false);} else {// if the parent class loader is empty, delegate to the startup class to load c = findbootstrapclass0 (name );}} catch (classnotfoundexception e) {// after the class loader or parent class loader throws an exception, the current class loader captures it // and uses the findclass method, load c = findclass (name) ;}} by yourself );}}

Use class. forname to load a class
Class. forname uses the called class loader to load classes.
This feature proves that the namespace in the Java class loader is unique and does not interfere with each other.
In general, ensure that all other classes associated with the same class are loaded by the class loader of the current class.

public static Class forName(String className)     throws ClassNotFoundException {     return forName0(className, true , ClassLoader.getCallerClassLoader());} /** Called after security checks have been made. */private static native Class forName0(String name, boolean initialize,ClassLoader loader)     throws ClassNotFoundException;

Classloader. getcallerclassloader is the class loader that obtains the class that calls the current forname method.

Thread context Class Loader
The default thread context class loader in Java is the system class loader (appclassloader ).

// Now create the class loader to use to launch the applicationtry {    loader = AppClassLoader.getAppClassLoader(extcl);} catch (IOException e) {    throw new InternalError("Could not create application class loader" );} // Also set the context class loader for the primordial thread.Thread.currentThread().setContextClassLoader(loader);

The above code is taken from sun. Misc. Launch's parameter-free constructor launch ().
With the thread context loader, You can discard the Parent-Child delegated loading chain mode in the execution thread and use the class loader in the thread context to load the class.
A typical example is to load the third-party library JNDI through the thread context, instead of relying on the parent delegate.
Most Java app servers (JBoss, tomcat...) also use contextclassloader to process Web Services.
Some frameworks that use the hotswap feature also use thread context class loaders, such as seasar (full stack framework in Japan ).

Thread context fundamentally solves the problem that general applications cannot violate the Parent-Child delegation mode.
Makes the Java class loading system more flexible.

With the advent of the multi-core era, I believe that multi-threaded development will increasingly enter the actual coding process of programmers. Therefore,
When writing infrastructure, loading classes by Using thread context should be a good choice.

Of course, there are advantages and disadvantages for good things. To Use thread context to load classes, you should also note that the class loaders between multiple threads that need to communicate should be the same,
Avoid type conversion exceptions (classcastexception) due to different classloaders ).

Custom Class Loader implementation
Defineclass (string name, byte [] B, int off, int Len, protectiondomain)
It is a Java. Lang. classloader provided to developers and used to customize the class loading interface.

This interface can be used to dynamically load class files.

For example,
In JDK, urlclassloader works with the findclass method to use defineclass. class can be loaded from the network or hard disk.

You can use the class loading interface and add your own implementation logic to customize more advanced features.

For example,

A simple Hot Swap Class Loader implementation:

Import Java. io. file; import Java. io. fileinputstream; import Java. lang. reflect. method; import java.net. URL; import java.net. urlclassloader;/*** the Class Loader with the same name can be reloaded. ** the load Chain Mode assigned by the parent is abandoned. * The State of the member variables of the class after the overload needs to be maintained externally. ** @ author Ken. wu * @ mail ken.wug@gmail.com * 01:37:43 */public class hotswapclassloader extends urlclassloader {public hotswapclassloader (URL [] URLs) {super (URLs);} public hotswapclassloader (u RL [] URLs, classloader parent) {super (URLs, parent);} public class load (string name) throws classnotfoundexception {return load (name, false );} public class load (string name, Boolean resolve) throws classnotfoundexception {If (null! = Super. findloadedclass (name) return reload (name, resolve); Class clazz = super. findclass (name); If (RESOLVE) super. resolveclass (clazz); Return clazz;} public class reload (string name, Boolean resolve) throws classnotfoundexception {return New hotswapclassloader (super. geturls (), super. getparent ()). load (name, resolve) ;}} public class A {Private B; Public void SETB (B) {This. B = B ;}public B getb () {return B ;}} public class B {}

The function of this class is to re-load the class with the same name, but in order to implement hotswap, the old object state
You need to copy it to the new instance generated by the overloaded class in other ways. (B instance in Class)

If the Class B on which the new instance depends is not loaded by the same class loader as the old object, a type conversion exception (classcastexception) will be thrown ).

To solve this problem, hotswapclassloader customizes the load method, that is, the current class is loaded by its classloader, and the internal dependent class is loaded by the classloader of the old object.

public class TestHotSwap {public static void main(String args[]) {    A a = new A();    B b = new B();    a.setB(b);     System.out.printf("A classLoader is %s n" , a.getClass().getClassLoader());    System.out.printf("B classLoader is %s n" , b.getClass().getClassLoader());    System.out.printf("A.b classLoader is %s n" ,   a.getB().getClass().getClassLoader());     HotSwapClassLoader c1 = new HotSwapClassLoader( new URL[]{ new URL( "file:\e:\test\")} , a.getClass().getClassLoader());    Class clazz = c1.load(" test.hotswap.A ");    Object aInstance = clazz.newInstance();     Method method1 = clazz.getMethod(" setB ", B.class);    method1.invoke(aInstance, b);     Method method2 = clazz.getMethod(" getB ", null);    Object bInstance = method2.invoke(aInstance, null);     System.out.printf(" reloaded A.b classLoader is %s n", bInstance.getClass().getClassLoader());}}

Output

A classloader is Sun. Misc. launcher $ appclassloader @ 19821f
B classloader is Sun. Misc. launcher $ appclassloader @ 19821f
A. B classloader is Sun. Misc. launcher $ appclassloader @ 19821f
Reloaded A. B classloader is Sun. Misc. launcher $ appclassloader @ 19821f

This article is reproduced, the original link: http://kenwublog.com/structure-of-java-class-loader

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.