ClassLoader working mechanism

Source: Internet
Author: User

First, the concept of ClassLoader

ClassLoader is used to dynamically load class files into a virtual machine, and converted to an instance of the Java.lang.class class, each of these instances is used to represent a Java class, we can get the information of the class according to the instance of class, and create an object of the class through the Newinstance () method of the instance, in addition, ClassLoader is also responsible for loading the resources needed for Java applications, such as files and configuration files.

The ClassLoader class is an abstract class. If a binary name is given to a class, the ClassLoader attempts to find or generate the data that makes up the class definition. The general strategy is to convert the name to a file name and then read the class file for that name from the file system. The ClassLoader class uses a delegate model to search for classes and resources. Each ClassLoader instance has a related parent class loader. When you need to find a class or resource, the ClassLoader practice delegates the task of searching for a class or resource to its parent ClassLoader before attempting to find the class or resource yourself.

Note: When the program starts, it does not load all the class files that the program will use at once, but instead dynamically loads a class file into memory according to the needs of the program through Java's class loading mechanism.

Second, the JVM platform provides three layer ClassLoader
    1. Bootstrap classLoader: Native code implementation, is a part of the JVM, the main load of the JVM itself to work on the required classes, such as java.lang.*, java.uti.*, etc., these classes are located in $java_home/jre/lib/ Rt.jar. Bootstrap ClassLoader does not inherit from ClassLoader, because it is not a normal Java class, the underlying is written in C + +, embedded in the JVM kernel, when the JVM starts, Bootstrap ClassLoader with the boot, After loading the core class library, and constructing the extension ClassLoader and the app ClassLoader class loader.
    2. Extclassloader: Extended class loader, loading an extension jar located in the $java_home/jre/lib/ext directory.
    3. Appclassloader: The System class loader, the parent class is Extclassloader, loads the directory and jar under $classpath, and it is responsible for loading the application main function class.

The architecture diagram is as follows:

  

If you are implementing your own classloader, whether you are implementing an abstract column ClassLoader or inheriting the URLClassLoader class, its parent loader is appclassloader, because no matter which parent class loader is called, The created object must eventually call Getsystemclassloader () as the parent loader, and the Getsystemclassloader () method gets to exactly appclassloader.

Note: Bootstrap ClassLoader does not belong to the hierarchy of the JVM, it does not comply with ClassLoader's load rules, Bootstrap ClassLoader does not have subclasses.

Third, the JVM load class files into memory in two ways
    1. Implicit loading: Instead of loading the required classes by calling ClassLoader in the code, the JVM will load the required classes into memory through the JVMs, for example: When a class inherits or references a class, the JVM automatically loads the classes into memory when it resolves the current class is not in memory.
    2. Display Load: Loads a class in code through the ClassLoader class, such as calling This.getClass.getClassLoader (). LoadClass () or Class.forName ().
Iv. process of ClassLoader loading classes
    1. Locate the. class file and load the file into memory
    2. Bytecode validation, class data structure analysis, memory allocation and symbolic table links
    3. static properties and initialization assignments in classes and execution of static code blocks
Five, custom class loader 1, why do you want to customize the ClassLoader?

The class loader provided by the JVM can only load the jar and class of the specified directory, and if we want to load classes or jars from other locations, such as loading a class file on the network, the default ClassLoader will not meet our needs, so we need to define our own classloader.

2. How to implement a custom ClassLoader?

We implement a classloader and specify the loading path for this classloader. There are two ways of doing this:

  Way One : Inherit ClassLoader, overriding the Findclass () method of the parent class, with the following code:

1 ImportJava.io.ByteArrayOutputStream;2 ImportJava.io.File;3 ImportJava.io.FileInputStream;4 Importjava.io.IOException;5  Public classPathclassloaderextendsClassLoader6 {7      Public Static FinalString drive = "d:/";8      Public Static FinalString FileType = ". Class";9 Ten      Public Static voidMain (string[] args)throwsException One     { APathclassloader loader =NewPathclassloader (); -Class<?> objclass = Loader.loadclass ("HelloWorld",true); -Object obj =objclass.newinstance (); the System.out.println (Objclass.getname ()); - System.out.println (Objclass.getclassloader ()); - System.out.println (Obj.getclass (). toString ()); -     } +  -      PublicClass<?>Findclass (String name) +     { A         byte[] data =loadclassdata (name); at         returnDefineClass (name, data, 0, data.length);//converts a byte array to Class//instances of the class -     } -      Public byte[] loadClassData (String name) -     { -FileInputStream FIS =NULL; -         byte[] data =NULL; in         Try -         { toFIS =NewFileInputStream (NewFile (drive + name +fileType)); +Bytearrayoutputstream BAOs =NewBytearrayoutputstream (); -             intCH = 0; the              while(ch = fis.read ())! =-1) *             { $ baos.write (CH);Panax Notoginseng             } -data =Baos.tobytearray (); the}Catch(IOException e) +         { A e.printstacktrace (); the         } +         returndata; -     } $}

In line 13th, we call the LoadClass () method of the parent class, which loads the class using the specified binary name, and the following is the source code for the LoadClass method:

protectedClass<?> loadclass (String name,BooleanResolvethrowsClassNotFoundException {synchronized(Getclassloadinglock (name)) {//The first step is to check if the class has been loadedclass<?> C =Findloadedclass (name); if(c = =NULL)            {                LongT0 =System.nanotime (); Try                {                    //Parent Loader                    if(Parent! =NULL)                    {                        //delegate the task of searching a class or resource to its parent class loaderc = Parent.loadclass (name,false); } Else                    {                        //Check if the class is Bootstrapclassloader loadedc =findbootstrapclassornull (name); }                }                 Catch(ClassNotFoundException e) {//ClassNotFoundException thrown if class not found//From the Non-null parent class loader                }                if(c = =NULL)                {                    //if the loaded class is not found in either of these steps, call the Findclass () method                    LongT1 =System.nanotime (); C=Findclass (name); //This is the defining class loader; record the statsSun.misc.PerfCounter.getParentDelegationTime (). Addtime (T1-t0);                    Sun.misc.PerfCounter.getFindClassTime (). Addelapsedtimefrom (t1);                Sun.misc.PerfCounter.getFindClasses (). increment (); }            }            if(Resolve) {resolveclass (c); }            returnC; }    }

  This method first checks whether the specified class has been loaded, if it has been loaded, calls the Resolveclass () method to link the specified class, or, if not already loaded, delegates the task of searching the class or resource to its parent classloader. Check if the class is loaded by Bootstrapclassloader, and if neither of the two steps have found the loaded class, then call the Findclass () method, in our custom loader, we override the Findclass method, Go to the path we specified to load the class file.

  In addition, our custom ClassLoader does not specify a parent loader, and the default is to use the System class loader, Appclassloader as its parent loader, without specifying the parent ClassLoader in the JVM specification, so that when using the custom class loader, the classes that need to be loaded cannot be in the classpath. Otherwise, the class to be loaded is loaded by the system ClassLoader, depending on the principle of the parent delegation model. If you want to put the class that the custom loader needs to load into the classpath, set the custom ClassLoader's parent loader to NULL.

  method Two : Inherit the URLClassLoader class, and then set the URL of the custom path to load the class under the URL.

We convert the specified directory to a URL path, and then override the Findclass method.

Vi. implementing a thermal deployment of a Class 1. What is a hot deployment of a class?

The so-called hot deployment is to upgrade the software while the app is running, without having to re-enable the app.

For Java applications, hot deployment is the runtime update of Java class files. Class loader plays an important role in implementing a hot deployment of Java-based application servers. Most Java-based application servers, including EJB servers and servlet containers, support hot deployment.

The class loader cannot reload a class that has already been loaded, but you can load the class again into a running application as long as you are using a new class loader instance.

2, how to implement the Java class hot deployment

In the previous analysis, we already know that the JVM checks whether the requested class has been loaded before loading the class, that is, to call the Findloadedclass method to see if the class instance can be returned. If the class has been loaded, then calling LoadClass will cause class conflicts.

However, the JVM determines whether a class is the same class with two conditions: one is to see if the class's full class name is the same (including the package name), and the second is whether the ClassLoader loader that loads the class is the same (two instances of the same ClassLoader class). Loading the same class will also be different).

Therefore, to implement a hot deployment of a class you can create a different instance object of ClassLoader, and then load the class with the same name through this different instance object.

Vii. References

  1, http://www.2cto.com/kf/201403/284030.html

ClassLoader working mechanism

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.