JVM Class Loader ClassLoader interpretation

Source: Internet
Author: User

The ClassLoader class loader is responsible for loading the class into the JVM.

The role of ClassLoader

(1) Loading class file into JVM
(2) Review who should be loaded by each class and adopt a parental delegation mechanism
(3) Re-parse the class bytecode into the object format required by the JVM

ClassLoader Structure Analysis

protected FinalClass<?>DefineClass(byte[] B,intOffintLenthrowsclassformaterror{returnDefineClass (NULL, B, off, Len,NULL); }protectedClass<?>Findclass(String name)throwsclassnotfoundexception {Throw NewClassNotFoundException (name); } PublicClass<?>LoadClass(String name)throwsclassnotfoundexception {returnLoadClass (Name,false); }protected Final void Resolveclass(class<?> c)    {RESOLVECLASS0 (c); }

(1) The DefineClass method is used to parse a byte stream into a class object that the JVM can recognize. If you use this method to create class objects directly, the class object is not resolve, and this resolve will be performed when the object is actually instantiated, usually in conjunction with the DefineClass method. If you want to be linked when the class is loaded into the JVM, you can call the Resolveclass method
(2) The ClassLoader class is an abstract class, and if we want to implement our own loader it will generally inherit the subclass URLClassLoader.

ClassLoader's parent delegation loading mechanism
Parent delegate loading mechanism that is, if a class of loaders receives a load request, it will first delegate the request to the parent ClassLoader to load, and if the parent determines that the class has not been loaded, it continues to delegate to its previous layer loader, which is the case for each level of the ClassLoader. All class load requests eventually reach the top-level classloader, and only the parent ClassLoader cannot load the request, and the subclass loads the class, which avoids repeated loading and prevents the user-defined class loader from replacing the Java core loader.

The three ClassLoader classes provided in the JVM, showing levels

(1) Bootstrap ClassLoader: The main load of the JVM itself is required to work on the class, fully controlled by the JVM itself, this class does not follow the parent delegation loading mechanism, it is just a class of loading tools, neither the parent loader nor the child loader.
(2) Extclassloader: The class itself is part of the JVM itself, but not implemented by the JVM itself, and the specific target of the service in the Java.ext.dirs directory class
(3) Appclassloader: This class serves the class Java.class.path directory, which is the classpath path.

  如果我们要实现自己的类加载器,不管是直接继承ClassLoader还是继承URLclassLoaderlei ,它的父加载器都是AppClassLoader,因为不管调用哪个父类构造器,创建的对象都必须最终调用getSystemClassLoader()作为父类加载器,而该方法获取的正是AppClassLoader。  如果应用中没有定义其他的类加载器,那么除了java.ext.dirs下的类是由ExtClassLoader来加载,其他的都是由AppClassLoader来加载。

Two ways that the JVM loads class files into memory

(1) Implicit loading: Instead of loading the required classes by calling ClassLoader in the code, the required class-to-memory mode is automatically loaded through the JVM. If the class inherits or references other classes in the class, when the JVM parses the current class, it finds that the reference class is not in memory and will automatically load the classes into memory.
(2) Display loading: Loads the class in code by calling the ClassLoader class. such as This.getclass (). getClassLoader () LoadClass () or class.forname () or our own implementation of the Findclass () method.

class Loading Process
Life cycle of a class

The following is the process of class loading

(1) First stage: Find the class file and load the byte code contained in the file into memory
(2) The second stage: bytecode verification, class data structure analysis and corresponding memory allocation, symbol table link.
(3) Phase III: Static property initialization assignment in classes and execution of static code blocks

Load bytecode into memory

Three things the JVM needs to do during the load phase:
(1) To obtain a binary byte stream that defines this class by using the fully qualified name of a class
(2) Transform the static storage structure represented by this byte stream into the runtime data structure of the method area
(3) Generate a Java.lang.Class object representing this class in the Java heap as the access entry for the data in the method area

In the abstract class ClassLoader, there is no definition of how to load, how to find the specified class and load it into memory in the subclass to implement it, that is, to implement the Findclass () method. such as in the URLClassLoader through a Urlclasspath class to load the class file byte stream, and this urlclasspath defines where to find the class file, if found this class file, The byte stream is then read by calling the DefineClass method to create the class object.

 protectedClass<?>Findclass(FinalString name)throwsclassnotfoundexception {Try{returnAccesscontroller.doprivileged (NewPrivilegedexceptionaction<class> () { PublicClassRun()throwsclassnotfoundexception {String path = Name.replace ('. ','/'). Concat (". Class"); Resource res = ucp.getresource (path,false);if(Res! =NULL) {Try{returnDefineClass (name, res); }Catch(IOException e) {Throw NewClassNotFoundException (name, E); }                        }Else{Throw NewClassNotFoundException (name);        }}}, ACC); }Catch(Java.security.PrivilegedActionException PAE) {Throw(classnotfoundexception) pae.getexception (); }    }

Validation phase

    验证是连接的第一步,这一阶段是为了确保Class文件的字节流中包含的信息符合当前虚拟机的要求,并且不会危害虚拟机自身的安全。验证阶段对虚拟机非常重要,但不一定是必要阶段。如果所运行的全部代码都已经反复验证过了,在实施阶段可以关闭大部分类的验证,以缩短虚拟机类加载的时间。

(1) The first step: file format verification, to verify that the byte stream conforms to the class file format specification, and can be processed by the virtual machine. For example, whether the magic number is 0xCAFEBABE
(2) The second step: metadata validation, the semantic analysis of the information of bytecode description, in order to ensure that its descriptive information conforms to the requirements of the Java language specification. For example, if the class has a parent class, whether the parent of the class inherits the class that is not allowed to inherit.
(3) The third step: bytecode verification, the most complex phase of the entire verification phase, mainly for data flow and control flow analysis, to ensure that the method of the calibration class will not be harmful to the virtual machine security behavior.
(4) Fourth step: symbol reference validation, this step occurs when the virtual machine converts a symbolic reference to a direct reference stage, which occurs in the resolution.

Preparation phase

   准备阶段是正式为类变量(被static修饰的变量)分配内存并设置变量初始值的阶段,这些内存都将在方法区中进行分配。这里仅仅包括类变量的内存分配,不包括实例变量,实例变量的内存分配将会在对象实例化时随着对象一起分配在java堆中。这里的初始值都是零值,如下代码中flag的初始值是false。
  publicstaticboolean flag=true;
 但是如果上述代码变成下面这样,那么在准备阶段变量flag就会被初始化为ConstantValue属性所指定的值,也就是true。
publicstaticfinalboolean flag=true;

parsing Phase
The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference. Parsing actions are mainly for classes or interfaces, fields, class methods, interface methods, and four types of symbolic references.

    • Symbol Reference: A symbol reference is a set of symbols to describe the referenced target, the symbol can make any form of the literal, as long as the use can be used without ambiguity to locate the target. Symbol references are independent of memory layout. The referenced target is not necessarily loaded into memory.
    • Direct reference: A direct reference can make a pointer directly to the target, a relative offset, or a handle that can be indirectly anchored to the target. The direct reference is related to the memory layout implemented by the virtual machine, and the direct reference that the same symbol reference translates on different virtual machines is generally not the same. If there is a direct reference, then the target of the reference must already exist in memory.

      Initialization phase

The initialization phase is the last stage of the class loading process, in addition to the class loading phase in which the user can participate through a custom loader, the rest of the actions are completely dominated and controlled by the virtual machine, and the Java program code defined in the class is really started at the initialization stage.
This stage is based on the programmer's subjective plan to initialize class variables and other resources, class variables are initialized to the default values, static code block to get executed.

Statement: This article is a lot of "in-depth analysis of javaweb Technology Insider" and "in-depth understanding of Java Virtual Machine" Summary, I hope that we have a lot of suggestions, common progress

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JVM Class Loader ClassLoader interpretation

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.