class loader in Java

Source: Internet
Author: User
Tags visibility

Reprint: http://blog.csdn.net/zhangjg_blog/article/details/16102131

from the Java dynamics to the class loading mechanism 

We know that Java is a dynamic language. So how do you understand this "dynamic"? Or what is the nature of a language that can be called a dynamic language? For Java, that's how I understand it.

We all know that the JVM (Java Virtual machine) does not execute a local machine code instruction, but rather executes an instruction called bytecode (which exists in the class file). This requires the virtual machine to load the relevant class file into memory before actually executing the bytecode. The virtual machine does not load all the required class files at once, because it does not know what class files will be used in the future when it executes. It is a class file associated with this class that is loaded "dynamically" at run time, with each of the classes used. This is the root cause of what Java is called a dynamic language. In addition to dynamically loading classes, classes are dynamically initialized and dynamically linked. Dynamic initialization and dynamic linking are described in other articles. This article only cares about the loading of classes.

The class loader (ClassLoader), which is responsible for loading classes in the JVM, is the class loader that this article describes, so the ClassLoader is an essential component of the JVM.

how ClassLoader and Class loaders work in Java 

In Java (referred to as javase) there are three kinds of loaders. Each class loader has specified their corresponding directories at the time of creation, that is, where each class loader goes to load the class is OK, I think there should be Gettargetpath () in the ClassLoader class, get their corresponding path, find the JDK's document, The discovery is not. Here are the three kinds of loaders and their corresponding paths:

* Appclassloader--load the class in the path specified by classpath

* Extclassloader-Class under the directory that loads the Jre/lib/ext directory or java.ext.dirs the system attribute definition

* BootStrap--load classes in Jre/lib/rt.jar

So how does the ClassLoader work? You can see the source code of the ClassLoader class in the JDK. The implementation of this class uses the template method pattern, first of all the LoadClass method to load the class, and the LoadClass method calls the Findclass method, which reads and returns the data of the class file, after the Findclass method returns, The LoadClass method continues to invoke the DefineClass method, which processes the returned data into the type information that is recognized by the virtual runtime. So, if we develop our own classloader, we just need to inherit the ClassLoader class from the JDK, and overwrite the Findclass method, and the rest of the work, the parent class will be done. Other Java platforms have implemented their own specific classloader based on their own needs, such as the Tomcat server in the Java EE platform, and the Dalvik virtual machine in the Android platform defines its own classloader.

There are two ways that a virtual machine loads a class, one is the Classloader.loadclass () method mentioned above, and the other is using the Reflection Api,class.forname () method, in fact Class.forName () The ClassLoader method is also used internally. The implementation of the Forname method in class classes is as follows:

 
  1. Public static class<?> forname (String name, boolean initialize,
  2. ClassLoader loader)
  3. throws ClassNotFoundException
  4. {
  5. if (loader = = null) {
  6. SecurityManager sm = System.getsecuritymanager ();
  7. if (sm! = null) {
  8. ClassLoader CCL = Classloader.getcallerclassloader ();
  9. if (CCL! = null) {
  10. Sm.checkpermission (
  11. Securityconstants.get_classloader_permission);
  12. }
  13. }
  14. }
  15. return FORNAME0 (name, initialize, loader);
  16. }
  17. /** called after security checks has been made. * *
  18. private static native Class FORNAME0 (String name, boolean initialize,
  19. ClassLoader loader)
  20. throws ClassNotFoundException;

three properties of the ClassLoader 

The ClassLoader has three features, delegate, visibility, and uniqueness, and the three features are described in the other articles below:

The delegate mechanism refers to the request to the parent class loader to load a class, and if the parent loader cannot find or load the class, then load it.

* The principle of visibility is that the classloader of the subclass can see all the classes loaded by the parent ClassLoader, and the parent ClassLoader does not see the class loaded by the child ClassLoader.

* The principle of uniqueness refers to loading only one class at a time, which is determined by the delegation mechanism to ensure that the subclass loader does not load the class loaded by the parent ClassLoader again.

Among them, the delegation mechanism is the foundation, in other materials also called this mechanism is the class loader's parent delegation model, actually said is the same meaning. Scalability and uniqueness are dependent on the delegation mechanism.

The following code tests the class loader's delegation mechanism:

 
  1. ClassLoader Appclassloader = classloadertest.  Class.getclassloader ();
  2. System.out.println (Appclassloader); //[email protected]
  3. ClassLoader Extclassloader = Appclassloader.getparent ();
  4. System.out.println (Extclassloader); //[email protected]
  5. Appclassloader's parent loader is Extclassloader
  6. System.out.println (Extclassloader.getparent ()); //null
  7. Extclassloader's parent loader is NULL, which is bootstrap, which is implemented by the C language

By printing the results, we know that loading our own class loader is Appclassloader,appclassloader's parent loader is Extclassloader, and Extclassloader's parent loader Returns a result of NULL, This means that his add-on is bootstrap, which is closely linked to the virtual machine, and the classes in the JDK are loaded when the virtual machine starts. It is implemented by C and does not have a corresponding Java object, so it returns NULL. But logically, Bootstrap is still the parent loader of Extclassloader. That is, whenever extclassloader loads a class, it is always delegated to bootstrap to load.

system class loader and thread context class loader 

In Java, there are two concepts, the system ClassLoader and the thread context class loader, respectively.

In fact, the System class loader is the Appclassloader application ClassLoader, it is two worth the same loader, the following code can be verified:

 
    1. classloader appclassloader  = classloadertest. class.getclassloader ();   
    2. system.out.println (appclassloader);  //[email  protected]  
    3.   
    4. classloader sysclassloader =  Classloader.getsystemclassloader ();   
    5. //[email protected]  
    6. //by the above validation, the,  application ClassLoader and the System class loader are the same,   Because the address is the same   


The output of these two class loaders is not only the same as the class name, but the hash value of the object is the same, which fully demonstrates that the system ClassLoader and application ClassLoader are not only the same class, but also the same object of the same class.

Each thread will have a context ClassLoader, which, by default, is the context class loader for the parent thread, that is, Appclassloader, because the class is loaded with the threads executing.

 
  1. New Thread (new Runnable () {
  2. @Override
  3. public Void Run () {
  4. ClassLoader Threadcontextclasslosder = Thread.CurrentThread (). Getcontextclassloader ();
  5. System.out.println (Threadcontextclasslosder); //[email protected]
  6. }
  7. }). Start ();

This sub-thread prints information as [email protected] when it executes, and you can see that the Appclassloader in the main thread is the same object (the hash value is the same).

You can also set a specific class loader for a thread, so that the thread executes using the particular ClassLoader to load the classes used. The following code:

 
  1. Thread th = new Thread (new Runnable () {
  2. @Override
  3. public Void Run () {
  4. ClassLoader Threadcontextclasslosder = Thread.CurrentThread (). Getcontextclassloader ();
  5. System.out.println (Threadcontextclasslosder); //[email protected]
  6. }
  7. });
  8. Th.setcontextclassloader (new ClassLoader () {});
  9. Th.start ();

Before the thread runs, a class loader object for an anonymous inner class is set for it, and the output information is: [email protected], which is the ClassLoader object we set.

the visibility of the class loader 

The following verifies the class loader's visibility, that is, the classloader of the subclass can see all the classes loaded by the parent ClassLoader, and the parent ClassLoader does not see the classes loaded by the child ClassLoader.

The following code uses the parent loader Extclassloader to load the class under the Appclassloader path of the sub-loader, which is impossible to achieve by the output.

 
  1. try {
  2. Class.forName ("Jg.zhang.java.testConcurrent.Person", true,
  3. Classloadertest.  Class.getclassloader (). GetParent ());
  4. System.out.println ("1-Class is loaded");
  5. } catch (ClassNotFoundException e) {
  6. //e.printstacktrace ();
  7. System.out.println ("1-no class found");
  8. }

Output is: 1-class not found. The description throws a ClassNotFoundException exception. The reason is to let Extclassloader load Jg.zhang.java.testConcurrent.Person This class because this class is not jre/lib/ In the Ext directory or java.ext.dirs The system attribute definition, so the classnotfoundexception is thrown. So the parent loader cannot load classes that should be loaded by the quilt loader. This means that the class is not visible in the parent loader. This mechanism relies on the delegation mechanism.

The following code uses the Appclassloader to load the class in the parent loader bootstrap, which is achievable.

 
  1. try {
  2. Class.forName ("java.lang.String", true,
  3. Classloadertest.  Class.getclassloader ());
  4. System.out.println ("2-Class is loaded");
  5. } catch (ClassNotFoundException e) {
  6. //e.printstacktrace ();
  7. System.out.println ("2-no class found");
  8. }


The output is: 2-the class is loaded. Description successfully loaded the string class. is because the Appclassloader has been delegated to the bootstrap load when the string class is specified to be loaded by Appclassloader. Although it is loaded by the child loader's parent loader, it can also be said that the class loaded by the parent loader is visible to the sub-loader. This also relies on the delegation mechanism. In fact, in the initial start of the virtual machine, Java.lang.String has been bootstrap pre-loaded, then loaded again, the virtual machine discovery has been loaded, will not be repeated loading. This also proves the singularity of the ClassLoader.

class loader in Java

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.