Java ClassLoader Detailed

Source: Internet
Author: User
Tags bootstrap classes

First, the class loading mechanism in Java has the following three properties:

1. Overall responsibility System

"Overall responsibility" means that when a classloader loads a class, the class that is dependent on and referenced by the class is also loaded by this claddloader unless the other classloader is used by the display.

For example, when the system ClassLoader Appclassloader loads the ingress class (the class containing the Main method), the class that the main method relies on and the class that is referenced are loaded, and so on. The "overall responsibility" mechanism can also be referred to as the current class loader responsible mechanism. Obviously, the class loader that the Ingress class relies on and the class to which it refers is the class loader for the Ingress class.

2. Parental delegation System (parent delegation)

1) Significance of the entrustment mechanism

Primarily for security reasons, make sure that the core class of Java has only one byte code in memory, For example, two classes A and B are to load the Java.lang.System class, through parental delegation, the system will only load once java.lang.System, even if the user rewrites Java.lang.System, there will be no opportunity to be loaded, unless you rewrite ClassLoader. Sometimes, however, in order to do container isolation, you need to have multiple byte codes for the same class in the JVM, such as OSGi and Pandora Technology, which will be discussed in detail later.

2) is the delegation mechanism necessary?

The "Parental delegation" mechanism is only a recommended mechanism for Java, not a mandatory mechanism. We can inherit the Java.lang.ClassLoader class and implement our own classloader. If you want to keep your parents delegating the model, you should override the Findclass (name) method, or you can override the LoadClass (name) method if you want to break the parental delegation model. Using your own ClassLoader, there are many advanced gameplay, such as the isolation mechanism of OSGi and Pandora, which is achieved through custom ClassLoader.

3) How to achieve parental delegation?

The default ClassLoader loadclass () implementation is the parental delegation model, we can inherit classloader to customize our own ClassLoader, and if you do not override the LoadClass method, the default is parental delegation. For example, URLClassLoader only implements Findclass (), and LoadClass () inherits ClassLoader, so it remains the parent delegation. Below is the Classloader.loadclass () source code, see how the parental delegation is implemented.

1) Check whether this class has been loaded, or if there is a direct return.

The loaded classes are cached so that the same class is not loaded two times, but there is a problem with what is the class cache key? In the JVM, class is uniquely identified with the class full name (package name + class name) plus the ClassLoader that loads the class, such as class full name C1,classloader is L1, then this class instance key in the JVM is ( C1, L1), at this time another ClassLoader L2 also loaded the class, then there will be another class instance (C1, L2), the two class instance is a different type, if the two class object is assigned to the operation of a value , there will be classcastexception.

2) try to load the class from parent ClassLoader.

3) If the parent is null (which is NULL when the parent is bootstrap), attempt to load the class from the Bootstrapclassloader native method.

4) try to load it yourself if the above attempt fails.

3. Load on Demand (On-demand Loading)

When will the class be loaded by the JVM? The answer is that the load, such as new instance, calls its static variable and method, or calls its class object using reflection, only when class is used.

This is easy to verify, with-verbose:class in the startup parameters, you can see clearly when the class was loaded.

Second, the order of ClassLoader loading class in the JVM

Third,the use of Contextclassloader

1) What is Contextclassloader

A property of thread that, at run time, can specify an appropriate ClassLoader as the contextclassloader of this thread, using the Setcontextclassloader method, Then use the Getcontextclassloader method anywhere to get this contextclassloader and load it into the class we need. If set is not displayed, the default is System ClassLoader. With this feature, we can "break" the ClassLoader delegation mechanism, and the parent ClassLoader can get the contextclassloader of the current thread, And this contextclassloader can be its son classloader or other classloader.

2) Why use Contextclassloader

Thread Context Classloaders provide a back door around the classloading delegation scheme.

Take JNDI for Instance:its Guts is implemented by bootstrap classes in Rt.jar (starting with J2SE 1.3), but these core J NDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application ' S-clas spath. This scenario calls for a, parent classloader (the primordial one in this case) to load a class visible to one of it child Classloaders (the system one, for example). Normal J2SE Delegation does not work, and the workaround are to do the core JNDI classes use thread context loaders, thus Effectively "tunneling" through the ClassLoader hierarchy in the direction opposite to the proper delegation.

This backdoor is useful in the implementation of the SPI because the interface class is loaded in the parent ClassLoader, and the implementation class is loaded by its child ClassLoader, using Contextclassloader to bypass parental delegation, Achieve the purpose of using the child ClassLoader to load class in the parent. The process is as follows:

Such examples are common in JDK, such as Jndi and JAXP, to load specific provider in such a way. For example

javax.xml.ws.spi.FactoryFinderObject Find (String Factoryid, String fallbackclassname) {ClassLoader ClassLoader; Try {            //Get context ClassLoader, mostly it ' s system ClassLoader, but it could is user-defined ClassLoader as well.ClassLoader =Thread.CurrentThread (). Getcontextclassloader (); } Catch(Exception x) {Throw Newwebserviceexception (x.tostring (), x); } String serviceId= "meta-inf/services/" +Factoryid; //try to find services in CLASSPATH//Note that if it's not the system ClassLoader, this would invoke user-defined ClassLoader ' s FindResource () to find Servic ES when all its parents failed.        Try{InputStream is=NULL; if(ClassLoader = =NULL) { is=Classloader.getsystemresourceasstream (serviceId); } Else{ is=Classloader.getresourceasstream (serviceId); }.....    returnnewinstance (Fallbackclassname, ClassLoader);}

Java ClassLoader Detailed

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.