In-depth understanding of Java Virtual Machine Learning notes 6--class loading mechanism

Source: Internet
Author: User
Tags call back

The Java Virtual machine class loading process is the process of loading the class file into memory and validating the data in the class file, parsing and initializing it, and finally forming a Java type that can be used directly by the virtual machine.

During the load phase, the Java Virtual machine needs to complete the following 3 things:

A. Get a binary byte stream that defines this class by using the fully qualified name of a class.

B. Convert the static storage structure represented by the binary byte stream that defines the class to the run-time data structure of the method area.

C. Generate a Java.lang.Class object representing the class in the Java heap as the access entry for the method area data.

Class loading for Java virtual machines is implemented through the ClassLoader, and the class loader architecture in Java is as follows:

(1). BootStrap ClassLoader: Starts the ClassLoader, is responsible for loading in the%java_home%\lib directory, or through the path specified by the-xbootclasspath parameter, and is recognized by the JAVA virtual machine (only according to the file name recognition, such as Rt.jar, the class library whose name does not conform, even if placed in the specified path will not be loaded) class library into the memory of the virtual machine, the startup ClassLoader cannot be directly referenced by the Java program.

(2). Extension ClassLoader: The extension class loader, implemented by Sun.misc.launcher$extclassloader, is responsible for loading the%java_home%\lib\ext directory, or all class libraries in the path specified by the JAVA.EXT.DIRS system variable, developers can use the extension class loader directly.

(3). Application ClassLoader: The application class loader, implemented by Sun.misc.launcher$appclassloader, is responsible for loading the class library specified on the user class path classpath. is the return value of the Getsystemclassloader () method in the ClassLoader ClassLoader, the developer can directly use the application ClassLoader, which is the default class loader in the program if there is no custom ClassLoader in the program.

Note: The class loader provided by the above three JDK is a parent-child classloader relationship, but does not use inheritance, but rather uses a composite relationship.

Starting with JDK1.2, the Java Virtual Machine specification recommends that developers use the Parental delegation mode (Parentsdelegation model) for class loading, which is loaded as follows:

(1). If a class loader receives a class load request, it first does not attempt to load the class itself, but instead delegates the class load request to the parent ClassLoader to complete.

(2). Each layer of the ClassLoader delegates the class load request to the parent ClassLoader until all the class load requests should be passed to the top-level startup class loader.

(3). If the top-level startup ClassLoader fails to complete the load request, the subclass loader attempts to load, and if the class loader that originally initiated the class load request cannot complete the load request, it will throw classnotfoundexception instead of calling its subclass loader to load the class.

The advantage of the class loading mechanism of the parent delegation mode is that the Java class has a hierarchical relationship with precedence, and the more basic classes are loaded by the upper class loader to ensure the stable operation of the Java program. Implementation of parental delegation mode:

[Java]View Plaincopy
  1. Protected synchronized class<?> loadclass (String name, Boolean Resolve) throws classnotfoundexception{
  2. //First check whether the requested class has been loaded
  3. Class C = findloadedclass (name);
  4. if (c = = null) {
  5. try{
  6. if (parent! = null) {//delegate parent ClassLoader load
  7. c = Parent.loadclass (name, false);
  8. }
  9. else{//Delegate startup ClassLoader load
  10. c = findbootstrapclassornull (name);
  11. }
  12. }catch (ClassNotFoundException e) {
  13. //Parent ClassLoader could not complete class load request
  14. }
  15. if (c = = null) {//itself class loader for class loading
  16. c = findclass (name);
  17. }
  18. }
  19. if (resolve) {
  20. Resolveclass (c);
  21. }
  22. return C;
  23. }

To implement a custom class loader, you only need to inherit the Java.lang.ClassLoader class and override its Findclass () method. The basic function of the Java.lang.ClassLoader class is to find or generate its corresponding byte code based on the name of a given class, and then define a Java class from those byte codes, which is an instance of the Java.lang.Class class. In addition, ClassLoader is responsible for loading the resources needed for Java applications, such as files and configuration files, and the methods associated with loading classes in ClassLoader are as follows:

method

description

getparent ()

loadclass (String name)

&NBSP;

findclass (String name)

Look for a class named  name , and the result is an instance of the  java.lang.Class  class.

 

findloadedclass (String name)

 

resolveclass (class<?> C)

Note: Before JDK1.2, class loading has not yet introduced parental delegation mode, so when implementing a custom ClassLoader, the LoadClass method is often overridden to provide parental delegation logic, and since JDK1.2, the parental delegation pattern has been introduced into the class loading system, and the custom ClassLoader does not need to write the parent-delegated logic in its own, and therefore does not encourage Overriding the LoadClass method, and recommending overriding the Findclass method.

In Java, any class needs to determine its uniqueness in the Java Virtual machine by the ClassLoader that loads it and the class itself, that is, to compare two classes for equality, only if the two classes are loaded by the same classloader, otherwise, Even though these two classes originate from the same class class file, the two classes must not be equal as long as the classloader that loads it is not the same (the equality here includes the Equals () method, the IsAssignableFrom () method, the Isinstance () of the class object representing the classes) Method and the result of the instanceof keyword). The example code is as follows:

[Java]View Plaincopy
  1. Package com.test;
  2. Public class Classloadertest {
  3. public static void Main (string[] args)throws exception{
  4. //Anonymous inner class implements a custom class loader
  5. ClassLoader Myclassloader = new ClassLoader () {
  6. protected class<?> Findclass (String name)throws classnotfoundexception{
  7. //Get class file name
  8. String filename = name.substring (Name.lastindexof (".") + 1) + ".   Class ";
  9. InputStream in = GetClass (). getResourceAsStream (filename);
  10. if (in = = null) {
  11. throw RuntimeException ("Could not found class file:" + filename);
  12. }
  13. Byte[] B = new byte[in.available ()];
  14. Return DefineClass (name, B, 0, b.length);
  15. }catch (IOException e) {
  16. throw New ClassNotFoundException (name);
  17. }
  18. };
  19. Object obj = Myclassloader.loadclass ("Com.test.ClassLoaderTest"). newinstance ();
  20. System.out.println (Obj.getclass ());
  21. System.out.println (obj instanceof com.test.  Classloadertest);
  22. }
  23. }

The output results are as follows:

Com.test.ClassLoaderTest

False

The reason instanceof returns false is because the Com.test.ClassLoaderTest class is loaded by default with application ClassLoader, and obj is loaded by a custom ClassLoader, and the classes are loaded differently and therefore not equal.

The class loader parental delegation model was introduced from JDK1.2 and is only a recommended model, not mandatory, so there are some exceptions that do not follow the parent delegation model:

(1). Prior to JDK1.2, the custom ClassLoader had to override the LoadClass method to implement the load class functionality, and after JDK1.2 introduced the parental delegation model, the LoadClass method was used to delegate the parent ClassLoader for class loading, and only the parent ClassLoader could not complete the class load request until its own Findclass method was called. Class is loaded, so the LoadClass method loaded by the class before JDK1.2 does not follow the parental delegation model, so after JDK1.2, the custom ClassLoader does not recommend overriding the LoadClass method, only the Findclass method is required.

(2). Parental delegation mode solves the basic class unification problem of each class loader well, the more basic class is loaded by the upper class loader, but this basic class has a lack of unification, when the base class wants to call back the user code of the lower layer, the subclass loader cannot be delegated to class load. To solve this problem, the JDK introduced the Threadcontext thread context, and the thread context class loader can be set through the Setcontextclassloader method of the thread context.

Java EE is only a specification, sun company only gives the interface specification, the specific implementation by each vendor implementation, so JNDI,JDBC,JAXB and so on these third party's implementation library can be called by the JDK class library. The thread context ClassLoader also does not follow the parental delegation model.

(3). In recent years, Hot code replacement, module thermal deployment and other applications require the code module Plug and Play without restarting the Java Virtual machine, the emergence of OSGi technology, in OSGi class loader system has been developed into a network structure. OSGi also does not fully follow the parental delegation model.

(GO) deep understanding Java Virtual Machine Learning Note 6--class loading mechanism

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.