Virtual Machine [JVM] class loading mechanism

What is the class loader
virtual machine to describe the class of data loaded from Class file into memory, and data validation, transformation and parsing initialization, eventually forming a Java type that can be directly used by the virtual machine, this is the class loading mechanism of virtual machines .

"[JVM] class file structure" talking about the Class file structure, namely Java code (.java files) after we write compiled Class files (.class files). This chapter describes how to load the Class file into memory and eventually the formation of a virtual machine directly using Java types.


1, class loading time

  • Class life cycle
Class life cycle

Wherein, loading, verification, preparation, and unloaded five initialization sequence is stationary, i.e., the class loading process begins in this order (but not performed in this order or complete, but for all stages of the cross).
In some cases the resolution phase will begin after the initialization: Binding (dynamic binding or late binding) in order to support the Java runtime.

The concept added: dynamic binding
Binding refers to the class and call a method where the method (method body) associate. For Java, the binding is divided into static binding and dynamic binding.
Static binding refers to the process of compiling already know that in the end this method is a method in which class, Java method which only final, static, private and construction methods are static binding. Dynamic binding means to bind the type specific object in the method of running a program. Java virtual machine can determine the type of the object during the operation, and calls the appropriate method.

  • Load timing
    virtual machine specification does not enforce constraints loading the first stage began when, but provides for and only five cases have to initialize the class immediately (while loading, validation, preparation naturally needs to be done before that). These five are as follows:
  • Encounter new, getstatic, putstatic, invokestatic when this four-byte code instructions, and the class had not been initialized. This generates four instructions Java code common scenario is: the use of the new keyword to instantiate an object when reading or setting a static field of a class (the final modified, except the results have been put into the constant pool of static fields at compile ) when calling a static method of class time.
  • Using the java.lang.reflectmethod package of classes reflection call time, if the class has not been initialized, you need to trigger initialization.
  • When initializing a class, if you find the parent class has not been initialized, you need to trigger the parent class initialization.
  • When the virtual machine starts, the user needs to specify a main class to be executed (including the main method of the class), the virtual machine to initialize this master class.
  • When using a dynamic language support JDK1.7 if an java.lang.invoke.MethodHandleinstance of the final analytical result REF_getStatic, REF_putStatic, REF_invokeStaticmethod handle, and this handle class corresponding method not been initialized, initialization is required to trigger it.

These five scenarios for the behavior of a class known as active references , in addition will not trigger initialization class, known as passive reference . With passive references are the following : ① by subclass reference a static field of the parent class, will not lead to a subclass initialization, will only lead to initialize the parent class; ② to refer to an array of class by definition, does not trigger initialization class ( but will trigger an array initialization); ③ constants at compile time will be credited to the constant pool class is called, there is no direct reference to the definition of the class constants of nature, it will not trigger initialization class defined constants.

Difference initialization interface initialization class: The class initialization, it requires the parent class has been initialized, but one interface at initialization, the interface does not require the parent to complete all initialization, only when the parent will really use interface initialization.


Class loading process

1, Load

In the loading phase, the virtual machine needs to be done three things:

  • Securing such binary byte stream
    in accordance with the fully qualified name of such acquisition, the main sources of Class binary stream files, ZIP package, network, compute runtime generated, generates other files such as JSP, database)
  • The binary byte stream is stored in the method area (stored according to a certain format).
  • Generating in memory a java.lang.Classsubject
    that will serve as the Class object methods to access various data entry area of this class, the virtual machine hotSpot the object is located in the process area.
2, verification

The purpose of verification is to ensure that the information byte stream file included in Class meet the requirements of the current virtual machine and the virtual machine will not jeopardize their own safety. Validation phase will be completed roughly an inspection operation following four stages:

  • File format check
    to verify that the phase is based on a binary byte stream, only through this stage, the byte stream will enter the process area memory for storage behind the validation phase area method is based on the storage structure carried out, it will not directly operate binary stream. Including: whether the magic number 0xCAFEBABEat the beginning, major and minor version number, etc. within the scope of the current virtual machine processing.

  • Metadata check
    purpose is to ensure that metadata information is not compliant with the Java language specification does not exist, including: whether the class has a parent class, whether inherited not allowed to be inherited class ( finalmodified class), whether realized or parent All methods required to achieve the interface, the fields and methods of the parent class if the contradictions.

  • Bytecode verification
    object is achieved by a data flow and control flow analysis to determine the semantics of the program is legitimate, logical, i.e., a method of analysis for verification class member.

  • Verification of symbolic references
    to class information itself other than matching check, occurs in the virtual machine when the symbol references into direct reference (parsing phase). Include: ① symbolic reference can be found whether the corresponding class is defined by the full name string description; ② whether or not there is a method in line with field descriptor and a simple method name and description fields specified class; class references symbol ③ , access method, whether the field can be accessed in the current class.

Validation phase is very important, but not necessarily essential stage, the code (the code I have written as well as third-party package) if the run has been repeatedly used and validated, consider using -Xverify:noneto shut down most of the class verification measures to shorten the time a virtual machine class load.

3, ready

Preparatory phase are: to allocate memory for class variables and class variables set the initial value . These variables are used by the memory in the method area allocated. To note are: ① static class variables are modified to be variable, not including instance variables, instance variables will be assigned together with the Java heap objects when the object is instantiated; ② the initial value normally refers to data type of zero value, but if it is static finalthe type of a variable, the value will be directly assigned to the code specified for that variable.

private int value = 123;//不会为该变量分配内存
private static int value = 123;//会为该变量分配内存并赋为零值(0) private static final int value = 123;//会为该变量分配内存并赋值为123 
4, parsing

Parsing stage work: the virtual machine constant pool of symbolic references to the process of replacing direct references. The main analysis operation for the class or interface, fields, methods class, interface method, type method, and calls the method handle points qualifiers.
Reference symbol : a set of symbols that describes the referenced target, literal symbols may be in any form, can be positioned unambiguously to use as long as the destination interface.
Direct reference : direct pointer to the object, a relative offset or indirectly targeted to handle targets.

  • Parsing the class or interface
    is assumed that the class where the current code is D, N To resolve symbolic references refer directly to a class or interface C, the whole process is divided into three processes:
    ① If the type is not an array C, the virtual machine N represents the fully qualified name passed to the D class loader to load the class. In the loading process, and may be loaded to the father of this class and other classes.
    ② If C is a type of an array, and the array of elements of type object, according to ① load the array element type, then the virtual machine to generate an array of objects and elements in this array represent the dimensions.
    ③ these steps were abnormal, then C has actually become a valid class or interface in the virtual machine. But also for access checks.

  • Field Analytical
    field symbol references resolved, will first symbol class or interface field belongs to a reference parses assumed normal analytical, the class of this field belongs or the interface represented by C, then the virtual machine C for subsequent fields in the following order Search: C itself, each interface or parent interface implemented in C (recursive), C inherits the parent class (recursively).
    If a field of the same name also appears in the C interface and the parent class, or simultaneously on a plurality of interfaces and their parent class, the compiler will refuse to compile.

  • Class analytical method

  • Interface method resolution

5, initialization

Initialization: really starts executing Java code (or bytecode) defined in the class.
During the preparation phase, the variable has been assigned an initial value once the system requirements, and in the initialization phase, to initialize the class variables and other resources in accordance with procedures specified by the programmer subjective plan: the initialization phase is the implementation class constructor <clinit>process approach . ( <clinit>Can be seen class init的简写)

About <clinit>method:

<clinit>is collected automatically by the compiler class assignment operation of all classes and static variables of the statement from the statement in the block were combined, collection order is order of appearance in the source file by the statement decision. Note: Static statement block only access to the static variables defined in a block of statements before, the definition of variables behind it, can be assigned, but can not be accessed as follows:

public class Test{
    static { i = 0;//赋值可以通过编译 System.out.print(i);//这句访问则会导致编译器报错:非法向前引用 } static int i = 1; } 

<clinit>method and class constructor (instance constructor <init>) different, it does not explicitly call the parent class constructor, the virtual guarantee in subclass <clinit>before execution method, the parent class's <clinit>method has already been implemented . Therefore, the first virtual machine to be executed <clinit>class method certainly java.lang.object.

③ As the parent class <clinit>method performed first, so static statements defined in the parent class block priority subclass in the variable assignment is performed .

<clinit>Method class or interface is not necessary, if a class is not a static block of statements, there is no assignment of class variables, the compiler may not be generated for the class <clinit>methods.

⑤ Interface block static statements can not be used, but there is still initialized variable assignment, and therefore generates the same class interface <clinit>methods. The difference is, that implements the interface <clinit>does not require the implementation of the parent class <clinit>method, only when the variable defined in the interface using the parent, the parent will be the interface initialization. Further, the interface implementation class initialization will not be performed when the interface <clinit>method .

⑥ opportunity to ensure a virtual class <clinit>method is correctly locked in a multi-threaded environment, synchronization. If multiple threads to initialize a class, then there will only be one thread to perform this type of <clinit>method, other threads are blocked need to wait until the active thread execution <clinit>method is completed next (the same class loader, a type initialization only once ). If a class <clinit>has a very time-consuming method of operation, multiple processes can lead to blockage.


Class loader

Acting class loader: acquiring description of such a binary byte stream through a fully qualified name of the class . This action is implemented in an external Java virtual machine, to allow the application to decide how to get the required categories. Class loader shine divided in the class hierarchy, the OSGi, hot deployment, code encryption, and other fields .

Class and class loader

For any category, you need to load it established by the class loader and the class itself with its uniqueness in the Java Virtual Machine : To compare the two classes whether "equal", only in these two classes are from the same class premise loader makes sense, or even if these two classes a class from the same file, is loaded with a virtual machine, as long as the class loader to load them different, and that the two classes will surely not equal.

Equal, including the object class Class represent classes referred to herein equals()methods, isAssignableFrom()a method, isInstance()the method returns the result, including the use of instanceofkeywords do relationship determining where the object belongs and the like.

Parent delegation model

From the perspective of the Java virtual machine is concerned , there are only two different class loaders:
① start class loader: Bootstrap ClassLoaderpart of its own virtual machine.
② other class loader: independent of external virtual machine, and all derived from the abstract class java.lang.ClassLoaer.

From the Java developer's perspective , the class loader can be divided in more detail, it is divided into four kinds:

  • Boot class loaderBootstrap ClassLoader
    responsible will be stored in <JAVA_HOME>\libthe directory, or by -Xbootclasspaththe parameters specified in the path, and a virtual machine identification library is loaded into the virtual machine memory. The developer does not directly reference the boot class loader, loaded if necessary delegates to the boot class loader, directly nullinstead of to.
  • Extension class loader isExtention ClassLoader
    responsible for loading <JAVA_HOME>\lib\extthe directory, or by java.ext.dirsall libraries, developer of system variables specified path can be used directly extend the class loader.
  • Application class loader
    also be called a system class loader, loading user class load path classpath, designated by the libraries, developers can use the class loader directly, if the application had no custom own class loader, general this is the case of the application of the default class loader.
  • Custom class loader

Applications are loaded with each other by four species loader, the relationship between them as shown below:

Parent class loader delegation model

This parent class loader hierarchy known as the class loader delegation model: In addition to the top of the boot class loader, the rest of the class loader should have its own parent class loader. Parent-child relationship between the class loader herein generally will not achieve inheritance relationship, but use a combination of the code multiplexing relationship with the parent loader.

Parent delegation model work process : If a class has received a request to load a class, it first does not own to try to load this class, but put this request to the parent class loader to complete each level of class loaders are It is so. Therefore, all requests are loaded from the top to start the boot class loader, loader feedback only when the parent they can not complete the loading request, subclass will try to load your own.

The benefits of using parent delegation model: Java class with its class loader together with a priority level with a relationship of, for example, to ensure that no two java.lang.Obejctclasses, the Java type system so as to ensure the most basic behavior, ensure the stable operation of Java programs.

Model implementation code (parents delegate java.lang.ClassLoader's loadClass()method):

protected Class<?> loadClass(String name, boolean resolve)throws ClassNotFoundException{
    synchronized (getClassLoadingLock(name)) {
        // 首先检查该类有没有被加载过 Class<?> c = findLoadedClass(name);// if (c == null) {//说明之前该类没加载过 long t0 = System.nanoTime(); try { if (parent != null) { //让父类加载器取加载 c = parent.loadClass(name, false); } else { //让启动类加载器去加载 c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { //发生ClassNotFoundException异常,则说明父类加载器没有加载成功 } if (c == null) {//为空,说明父类加载器没有加载成功 long t1 = System.nanoTime(); //调用自身findClass(String name)方法去进行类加载 c = findClass(name); // this is the defining class loader; record the stats sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { resolveClass(c); } return c; } } 
Parents damage delegation model (// todo)
  • The first
    occurs before appeared before the parent delegation model that JDK1.2 release. When a custom user class loader, override loadClass()methods to achieve own class loader logic. Now, after JDK1.2 no longer advocate the user override this method, because this method is the key model implementation delegated parents, but allow users to rewrite findClass()method.
  • The second
    model itself lead to defects, such problems can not be solved user code to call the base class, such as JNDI service ( Java Naming and Directory Interface).
  • The third
    hot code Alternatively, thermal module deployment.

Content from "in-depth understanding of the Java Virtual Machine": VM class loading mechanism



Author: maxwellyue
link: https: //www.jianshu.com/p/03dec949d01b
Source: Jane books

Guess you like

Origin www.cnblogs.com/xiaoshen666/p/11258567.html