Java ClassLoader Concepts and threading Class loaders

Source: Internet
Author: User

The function of the ClassLoader: the process of obtaining a binary byte stream describing this class by fully qualified name of a class Java ClassLoader can be broadly divided into two categories, one for the system, and one for the application developer. There are three types of classloader available in the system: Boot ClassLoader (bootstrap class loader): The core library (Rt.jar) used to load Java, which is implemented with native code and does not inherit from java.lang.ClassLoader。 Extension class loader (Extensions class loader): The extension library used to load Java. The implementation of the Java virtual machine provides an extension library directory. The ClassLoader finds and loads the Java class in this directory. Application (System) class loader (Application class loader): Loads Java classes based on the Classpath (CLASSPATH) of the Java application. In general, Java-applied classes are loaded by it. There's also a developer-defined class loader. The parent delegation principle is used when the system is loading classes. The working process of the parent delegation principle:If a class loader needs to load a class, it does not attempt to load the class itself, but the new load request is delegated to its parent ClassLoader to complete. The same parent class loader will delegate the request to its parent class until the top-level bootstrap class Loader, and the bootloader can attempt to load the class file as requested. If the load class file fails, it is reversed by its child loader to try to load until the successful sub-loader can be loaded. The order of simplification is as follows: Custom ClassLoader, Application classloader, extension class loader, boot class loader What are the advantages of the parent delegation? By using the parent delegation, you can guarantee that the Java program's stabilizer, Java judgment is the same class, will require two classes must be loaded by the same class loader. Without the principle of the parent delegation, for the same class, it may be loaded by multiple ClassLoader. and each class loader loaded into the class, the virtual machine is identified as different classes, it can be imagined, so how many operations and methods can not be executed. the implementation code of the parent delegation?
protected synchronizedClass<?> loadclass (String name,Booleanresolve)throwsClassNotFoundException {//First , check if the class has already been loadedClass C =Findloadedclass (name); if(c = =NULL) {         Try {            if(Parent! =NULL) {C= parent. LoadClass (Name,false); } Else{C=findbootstrapclassornull (name); }         } Catch(ClassNotFoundException e) {//ClassNotFoundException thrown if class not found//From the Non-null parent class loader            }            if(c = =NULL) {             //If still not found, then invoke Findclass in order//To find the class.c =Findclass (name); }     }     if(Resolve) {resolveclass (c); }     returnC; }
View Codeas the above code shows, the implementation of the parent delegation is very simple, firstFindloadedclass (call the native method) to find whether the class has been loaded, or if the class is not loaded, byParent. LoadClass (Name, false); Load class, only the parent loader is not loaded successfully, it is loaded by the current class loader. Special Case- thread Context class loader :for most class loading can be done through the parent delegation way to the reality, but there is no special case? For example: The Jndi interface is in the Rt.jar package, RT is the Java core class, and its loading is done through bootstrap class loader. However, the implementation of JNDI is provided externally and is not part of Rt. Classes in non-RT packages are not visible to bootstrap class loader and cannot be loaded. That's in the loadJndi interface at the same time, how to load the implementation of Jndi? At this point, the thread context class loader can be implemented,the thread context class loader is not a real ClassLoader, which is relative to the current class loader. It is more appropriate to define the thread context ClassLoader as a way of doing it, and the thread context class loader is actually ain the context of the parent ClassLoader, the way the child ClassLoader is called。 On the surface seems to conflict with the parent delegation, in fact, the parent class can not directly invoke the subclass loader, the child class loader is called, only in the current ClassLoader is the parent class loader thread environment, through the current thread of the Getcontextclassloader () method to get the other classloader. Examples are as follows:
1  PackageCom.csair.soc.thread;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 6  Public classMyclassloaderextendsclassloader{7 @Override8       PublicClass<?> loadclass (String name)throwsClassNotFoundException {9             Try {TenString fileName = name.substring (Name.lastindexof (".") + 1) One+ ". Class"; AInputStream is = This. GetClass (). getResourceAsStream (fileName); -                  if(IS = =NULL) { -                       return Super. LoadClass (name); the                 } -                  byte[] B =New byte[Is.available ()]; - Is.read (b); -                  returnDefineClass (name, B, 0, B. length); +}Catch(IOException e) { -                  Throw Newclassnotfoundexception (name); +            } A      } at}
View Code
1  PackageCom.csair.soc.thread;2 3  Public classThreadcontexttest {4       Public Static voidMain (string[] args)throwsClassNotFoundException {5ThreadTest TT =Newthreadtest ();6             //to set the context class loader for a thread7Tt.setcontextclassloader (NewCom.csair.soc.thread.MyClassLoader ());8 Tt.start ();9      }Ten       Public Static classThreadTestextendsthread{ One           Public voidrun () { A                  Try { -System. OUT.PRINTLN ("Thread Context class loader:" +Getcontextclassloader ()); -System. Out.println ("Current class loader:" + This. GetClass (). getClassLoader ()); theclass<?> Class1 = Getcontextclassloader (). LoadClass ("Com.csair.soc.thread.ThreadContextTest" ); -System. Out.println ("Loading class loader:" +Class1.getclassloader ()); -}Catch(ClassNotFoundException e) { - e.printstacktrace (); +                 } -          } +      } A}
View CodeOutput Result:thread Context class loader: [email protected]Current class loader: [email protected]class loader loaded with class: [Email protected] The thread-context ClassLoader solves the problem of Jndi loading, and in the current class loader's bootstrap class loader thread environment, the thread gets the pre-set thread class loader through the Getcontextclassloader () method ( Application class loader), to load the Jndi implementation class. How does ClassLoader hold entity classes? Why does the entity class also be unloaded after ClassLoader unload ? ClassLoader willhas its own namespace, and the namespace consists of all classes with this loader as the initiating class loader。 For class unloading,the exact words of sun Company areSo say: "Class or Interfacemay be unloaded if and only if it class loader is unreachable. Classesloaded by the bootstrap loader will be unloaded. When a class's loader is recycled by GC, the class can be uninstalledWhat is the difference between class.forname () and Classloader.loadclass, the first time new XXX (), how to load Class? Java provides two ways to load a class1, stealth loading, such as new XXX () way to implicitly load class2, display loading,Forname () method in Java.lang.Class, Java.lang.ClassLoader loadclass ()Forname actually calls the native method,FORNAME0 (ClassName, True, Classloader.getcallerclassloader ()); Loads the className through the current class loader. The second parameter, True, indicates whether the class is initialized when the class is loaded, that is, the statement that invokes the static block of the class and initializes the static member variable.when you use LoadClass to load a class, the class is not initialized by default.
The class loader conforms to the principle of the parent delegation, and the custom ClassLoader, why can I load class?Custom ClassLoader, you can override loadclass non-compliance with the parent delegation principle. In addition, some class files are not visible to the class loader of the system, or the system's ClassLoader cannot find the class file, at which point the custom class loader finds the class file with a custom Findclass method.

Java ClassLoader Concepts and threading Class loaders

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.