JVM knowledge - in-depth understanding of JVM class loader

Preface:

  Added to the previous Java program actually will. class file into the JVM run. The virtual machine data that describes the classes loaded from Class file into memory, and verify the data, conversion, and parsing initialization, the Java type can be eventually used as a virtual machine, which is the JVM class loading mechanism

First, the class loading process

  Class from start to load the virtual machine memory to unload a far memory, life cycle includes: loading, validation, preparation, parsing, initialization, use and uninstall.

1, Load

  To obtain such a binary byte stream defined by the fully qualified name of a class (not specified binary stream of bytes from a file acquisition Class, the packet may be read from ZIP, acquired from the network, generating a computing operation or other etc.) that represents a byte stream static storage structure into a run-time data structure in memory area method generates a representative of this class java.lang.Class objects , as various methods of data access region of the inlet of the class after completion, the external binary stream of bytes to the virtual machine a virtual machine in accordance with the desired format stored in the method area. Here a little understanding about the concept of objects and classes, an object class is instantiated. Category information is stored in the method area of the object is stored in the Java heap. Class is a template object, the object is an instance of the class . Here is mainly about class.

2, verification

** loading phase is not complete, the connection phase has begun. It will run cross between the two. ** Because the Class file can be produced in any way, do not meet the constraints Class byte stream file format, the virtual java.lang.VerifyError throw an exception, so in order to protect the virtual machine, JVM will verify the following four areas

  File format validation: the validation class file structure

  Metadata validation: This Is there a parent, if the parent is not allowed to inherit the inherited class, etc.  

  Bytecode verification: the procedure for verification class body, simply by checking the record StackMapTable property after the legality of JDK1.6, JDK1.7 for the major version number is greater than 50 Class document, type checking is done using the data stream analysis

  Verification of symbolic references: to find whether the fully qualified name corresponding to the class, whether the present field and the methods described meet the simple name described in the field of the specified class. Accessibility is correct. Java.lang.incompatibleClassChangeError verification unsuccessful throws an exception subclasses.

3, ready

  Officially assigned a class variable phase memory and set the initial value of the class variable , these variables are used in the memory area allocated in the process. This time includes only memory allocation class variables (static variables modified), do not include instance variables, instance variables is allocated when the object is instantiated along with the objects in the heap in Java . At this time the initial value assigned to a zero value, assuming a variable is defined as: public static int value = 123; the initial value of the variable is set to be 0, 123 instead. Assigned the value of 123 is putstatic instruction after the program is compiled, stored in the class into the constructor () method, the value will be assigned to the operation 123 will be performed during the initialization phase . If there is ConstantValue property field attribute table, then assign a value ConstantValue attributes specified in the preparation phase will value. For example: public static final int value = 123 ; then the preparation phase, will be assigned to the value 123;

4, parsing

  The process of converting direct symbol references cited. Symbol references a set of target symbols is described in the referenced, literal symbols may be in any form, can be used as long as the unambiguous target to target. Symbol reference has nothing to do with the memory layout to achieve a virtual machine, the goal is not necessarily a reference has been loaded into memory. Direct pointer reference can be a direct target, a relative offset or indirectly targeted to handle targets. And is a direct reference to the memory layout of the virtual machine implementation of relevant references translated in a different virtual machine instances are generally not the same as a direct reference to a symbol. If you have a direct reference to that target reference must already exist in memory.

  Parsing action aimed at: reference a class or interface, field (class member variables), class methods, interfaces, methods, etc.. 

  Parsing the class or interface: determining a desired direct reference is converted into an array type, or a reference to a common type of object so as to perform different analysis.

  Fields Analysis: When the field is parsed, it will first look for simple field contains the name and field descriptors are matched to the target in this class, if so, to find the end; if not, it will follow on from the inheritance down recursive search interfaces and their respective parent interface class is implemented, yet, according to the inheritance recursive search downward from the parent class, until the search ends, the flow look as shown below:

  One final note: in theory, the search to resolve the above order, but in practical application, virtual machine compiler implementation may be greater than the above regulatory requirements more stringent. If there is a field of the same name also appears in the class interface and the parent class, or also appear in the interfaces themselves or the parent class, the compiler might refuse to compile.

  Class Analytical Method: Analytical method and the class of the field is parsed search step, only in a more determining the class or method step in which the interface, and the class matching search method, the search is the first parent class, then the search interface.

  Interface Analytical Method: Similar analysis step and class methods, since the interface will not have a parent class, and therefore, only the parent interface recursive search direction on the line.

5, initialization

  The final step is a Java program's class loading process, to this stage, really started classes defined in the code. During the preparation phase, class variables had been assigned an initial value once the system requirements, and in the initialization phase, is to initialize class variables and other resources in accordance with procedures specified by the programmer subjective plan. To the initial stage, only really began to execute Java code class. I.e., the initialization phase is performed during the class constructor () method. 

  () Method resolution process: The method is compiler automatically collected assignment operation class for all class variables and static block of statements (static {} block) statements merger, the order compiler by the statement in the source file the order of appearance of the decision, so the static statements can only access the block to define variables in static statements before the block , define variables behind it, in front of a static blocks can be assigned, but can not access. Virtual opportunity to ensure that before the subclass () method executes, the parent class () method have been implemented, and therefore class () method in a virtual machine to be executed must be java. lang. Object . () Method for the class or interface is not essential, if a class is not a static block of statements, there is no assignment of the variables, the compiler may not be generated for the class () method . So this () method is mainly to perform static and static variable assignment statement block . Interface block static statements can not be used, but there is still initialized variable assignment, and therefore generates different interfaces and classes () method, but different interfaces and classes that implements the interface () method does not need to run a parent interface ( )method. Only when the parent variables defined in the interface using parent interface will be initialized. Further, the interface implementation class will not be the same () interface method performed at initialization.

  Virtual opportunity to ensure a class () method is properly locked in a multi-threaded environment, synchronization, if multiple threads to initialize a class, then there will only be one thread to perform this class () method, all other threads need to block waiting until the active thread execution () method is completed. If you have a long time-consuming operation in a class () method, it may cause multiple processes blocked in the practical application of this blockage is often very subtle.

summary:

  For now loading phase it is to obtain information class, class verification phase to verify compliance with the standard JVM. These two stages can be cross run. Then you need to type in the preparatory stage to allocate memory space, set the constant initial value of the static variable, and so on. The resolution phase is converted to a direct reference to symbolic reference, so that class is associated with memory on JVM. Finally, the initialization phase is the implementation class Static variables and static assignment block. Here are some of the class-based work has been completed, ready for use.

Two, Java class loader and the parents delegate mechanism

  To achieve "for descriptions of such binary byte stream through a naming authority class" load the action code module called a class loader java class is done by the virtual machine, the virtual machine loads a file that describes the classes Class to memory, and to verify the data, and parsing initialization, forming java java virtual machine type can be used directly, that is class loading mechanism of the virtual machine. The JVM for the above functions is embodied class loader. Class loader reads. byte code class file to convert it into java. lang. An instance of class Class. Each instance of the class used to represent a java. By this example newInstance () method to create an object of that class.

1, the bootstrap class loader (Bootstrap ClassLoader)

  This class loader is responsible for loading <JAVA_HOME> \ library lib directory to the virtual machine memory, used to load core java library class loader is not inherited from java.lang.ClassLoader, can not be directly java program calls, the code is written in C ++. It is part of the virtual machine itself

2, extension class loader (Extendsion ClassLoader)

  This class loader is responsible for loading <JAVA_HOME> \ library under the lib \ ext directory, used to load the java extension libraries, developers can directly use this class loader.

3, application class loader (Application ClassLoader)

  This class loader is responsible for loading the user class path in the library (CLASSPATH), generally we write java classes are loaded by the class loader, the class loader is the return value getSystemClassLoader CLassLoader in () method, so it The system is called class loader. Under normal circumstances this is the default class loader

4, a custom class loader

  This loader loads meet the special needs of our class, the class needs to inherit java.lang.ClassLoader and cover them findClass () method and defineClass () method.

5, parents delegate mechanism

  The above four loader is not loaded in parallel, JVM parents is by delegating the mechanism to load:

  Parent delegation model is a specification for an organizational relationship between the class loader, its working principle is: if a class loader loads the class received a request, it does not own to try to load this class, but this delegates to the parent class loader to complete, so progressive layers, eventually all load requests are passed to the topmost class loader to start, only when the parent class loader can not complete the loading request (its search within the required class is not found), will be handed over to the child class loader to attempt to load . The advantage is: java class as it has the class loader hierarchy together with priority. This is necessary, such as java.lang.Object, it is stored in the \ jre \ lib \ rt. jar, it is the parent of all java class, so no matter which class loader loads the class should be the final summary of all requests are loaded to the top of the boot class loader. Object class will be loaded by the boot class loader, so the load is the same class, if you do not use the parent delegation model, by each class loader to load their own words, the system will appear in more than one class Object, the application It will be all messed up.

Third, the class must be initialized in five cases

  1, encounter new, getstatic, putstatic, invokestatic bytecode instructions. The most common scenario is the Java code: using new instance of the object, or to read a class static field is provided (except for the final modified compiler or the result into the constant pool static field), a static method call class

  2, java.lang.reflect package using a method based on the reflecting call

  3, the class inherits the parent, the parent class must first initialize

  4, the virtual machine starts, initialize the master class

  5, when a dynamic language support JDK 1.7, if a final example of the analysis result java.lang.invoke.MethodHandle REF_getStatic, REF_putStatic, REF_invokeStatic the method handle, and this method handle class corresponding not been initialized, it is necessary first triggers its initialization.

Reproduced in: https: //juejin.im/post/5cf0f8d5f265da1b70048f8e

Guess you like

Origin blog.csdn.net/weixin_34405332/article/details/91459915