Java Virtual Machine - class loading mechanism

Outline

The virtual machine data that describes the classes loaded from Class file into memory, and data validation, parsing and conversion initialization, forming Java type can be used as a virtual machine, which is a virtual machine class loading mechanism.
Without connection work when compiling, loading, connectivity and initialization of the class is done during program execution. The interface for the application can wait until the specified actual implementation class runtime; user may pre-defined or the class loader custom for local application can be loaded from the network, or elsewhere during operation a binary stream as a portion of the program code.

Class loading time

Classes begin to be loaded into the virtual machine memory, to unload a far memory, life cycle includes: Load (Loading), verification (Verification), preparation (Preparation), analytical (Resolution), initializing (Initialization), using (Using) and unloading (unloading) 7 stages.

load

Five cases of the class must be initialized immediately:

  1. Examples of the use of new objects, to read or set a static field of a class (except in the final modified static field and compile the results into the constant pool), a static method call class.
  2. Java.lang.reflect package using a method based on the reflecting invoked, the corresponding class is not initialized, it is necessary to trigger its initialization.
  3. When initializing a class if its parent is not initialized, you need to trigger initialization of the parent class.
  4. When a virtual machine is started, the main class user specifies a class to be executed, the virtual machine to initialize this class.
  5. If java.lang.invoke.MethodHandle JDK1.7 a final result of the analysis method of Example handle position REF_getStatic, REF_putStatic, REF_invokeStatic, and this method handle corresponding to the class has not been initialized, initialization thereof needs to be triggered.
    In addition to the five above than all other reference will not trigger initialization, known as passive reference.

Class loading process

Process includes loading, validation, preparation, analytical, initializing five phases

load

Loading phase, the virtual machine is mainly to complete the following three things:

  1. To obtain such a binary byte stream defined by the fully qualified name of a class.
  2. This byte static storage structure represented by the data structure into the method area runtime.
  3. Generating in memory represents java.lang.Class object of this class, as a method for accessing the various data entry areas of this class.

Get Class name of the class defined by the full binary byte stream of a variety of ways, such as:

  1. Read from the Zip, Jar, Ear, War other packet types.
  2. Obtained from the network types, Applet.
  3. Calculates and generates run-time, dynamic agent technology.
  4. Other file generation, such as JSP
    , etc.

Non-array type can be used to provide the bootstrap class loader system is completed, can be user-defined class loader (rewritable class loader loadClass () method)
array class is not created by a class loader, directly created by the virtual machine.

verification

The first step is to verify the connection phase, the purpose of this stage is to ensure that the information byte stream file containing species Class meets the requirements of the current virtual machine and the virtual machine will not jeopardize their own safety.

  1. File format validation (make sure that the class file structure in line with the standard JVM)
  2. Metadata validation (authentication metadata information such that the data type, information conforms to Java specifications, whether a parent class, whether the method implemented in the interface, whether the overloaded rules, etc.)
  3. Bytecode verification (the data flow and control flow analysis to determine semantics of the program is legitimate, to verify the analysis method body, e.g. the type of security, the jump instruction can not be free)
    at the Halting Problem (downtime) application logic is unable to verify be absolutely accurate.
  4. Verify reference symbols (classes, fields, whether the access method)

ready

Preparation phase is formally allocate memory for class variables and set the stage class variable initial values ​​of these variables used in memory will be allocated in the method area seed.

Resolve

Parsing stage is a virtual machine to a constant pool of symbolic reference procedure replaces bit direct references, symbols referenced in the Class file types to CONSTSNT_Class_info, CONSTSNT_Fieldref_info, CONSTSNT_Methodref_info and other types of constants emerge.
Reference symbol (Symbolic References): Symbol reference to a certain set of symbols described in the referenced, literal symbols may be in any form, can unambiguous target as long as the target can be used.
A direct reference (Direct References): direct reference may be direct pointer to the object, 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 cited directly translated in a virtual machine instance with a different symbol is generally not the same, if there is a direct reference to that target reference must already exist in memory.

  1. Parsing class or interface
    of Hypothesis is D, never take a parsed N resolve symbolic references refer directly to a class or interface C, the parsing process in three steps:
    . 1) is not an array type C, the virtual machine N the fully qualified name passed to the D class loader to load a class in C, procedures in the event of abnormal, analytical failed.
    2) C is the array element type is the object type and, according to the type of array elements loaded rules 1, then generates an array of objects by the virtual machine and the dimensions of this array of elements representative.
    3) The above two steps without any exception, in the VM C has become a valid class or interface, but also for verification of symbolic references parsed before, D is confirmed to have access to the C.

  2. Fields resolve
    resolve field symbolic references, first in the field in the table class_index index of CONSTANT_Class_info symbolic references to parse, is the class or interface symbolic references, if occurred during the disorder can cause resolution failure, like if successful this field belongs to, or interfaces to C represents a follow-up operation is:
    1) C itself contains the field names and field descriptors are simply match the target of a direct reference to return to the field to find the end of the
    2) If C implements the interface will look from the bottom up according to inheritance, If you find a direct reference to find the end of the
    3) If C is not a java.lang.Object, in accordance with the inheritance look up from the bottom, if you find a direct reference to find the closing
    4) did not find, throw java.lang.NoSuchFieldError. If you find but also to determine whether access

  3. Class analytical method
    and analytical fields similar, we assume that the class associated method resolves successfully is C, the subsequent operation:
    1) If it is found in the class method table index C is class_index interfaces, throw java.lang.IncompatibleClassChangeError, i.e. the method is not a class or interface method abstract methods that must be implemented.
    2) If the first step is no problem, then find whether there is a simple name and descriptors are matched with a target, if found to find a direct reference to the end of the class C
    3) or recursive search in the parent class C, if found directly find the end of the reference
    4) or recursive query interface list and parent interface C, if C is find a description of an abstract class, find the end of the java.lang.AbstractMethodError throw an exception.
    5) are not found, throw java.lang.NoSuchMethodError, if it finds but also to determine whether access

  4. Analytical Method interfaces
    and classes similar methods, a method of setting interface for parsing relevant to the success of C, the subsequent operation:
    1) If the index C is found class_index a class rather than an interface, throw java.lang.IncompatibleClassChangeError
    2) in the interface C find directly, if found a direct reference to find the end of the
    3) recursive search in the parent Interface Interface C, until java.lang.Object class, if found to find a direct reference to the end of
    4) are not found, throw java.lang.NoSuchMethodError, interfaces the default method is public, and therefore do not have access problems

initialization

Class initialization is the final step of the class load, execute Java code here (or bytecode) defined in the class. Initialization phase is performed class constructor () Process approach. This combined method is automatically collected by the compiler of the class assignment operation and static variables of all classes statement block statement made.
() Class constructor method () Different methods, need to explicitly call the parent class constructor, the virtual guarantee subclass () Before performing the method, the parent class () Has been executed, the first to be executed () Method must be java.lang.Object.

Class loader

The virtual machine class loader stage "to get through the fully qualified name of a class description of such a binary byte stream" this action to the outside Java virtual machine to achieve, let the application decide how to get bytes needed class that implements the action code module called a "class loader."

Class and class loader

Any class to be established by the loaded his class loader and the class itself with its uniqueness in the Java virtual machine, each class loader has a separate class namespace. Two classes are equal, you need a Class from the same file, is loaded with a virtual machine, the same class loader.

Parent delegation model

Java Virtual Machine exists only in two different class loaders: one is to start class loader (Bootstrap ClassLoader), the class loader uses the C ++ language, is part of the virtual machine itself; the other is for all other class loaders , a class loader by these Java language, independent of external virtual machine, and all derived from the abstract class java.lang.ClassLoader.
According to a more detailed sub-method, most Java programs will use the following three kinds of system-provided class loader.

  1. Start class loader (Bootstrap ClassLoader)
    This class loader is responsible will be stored in \ Lib directory, or by -Xbootclasspath parameters specified path, and a virtual machine identification (by file name recognition as rt.jar, even if the name does not meet on the path will not be loaded only) start class loader can not be directly referenced Java programs.
  2. Extension class loader (Extension ClassLoader)
    This class loader is implemented by sun.misc.Launcher $ ExtClassLoader, responsible for loading \ Lib \ ext directory, or by all libraries, developers java.ext.dirs system variables specified path can be used directly extended class loader.
  3. Application class loader (Application ClassLoader)
    the class loader is implemented by sun.misc.Launcher $ AppClassLoader, the class loader is the return value of getSystemClassLoader ClassLoader () method, it is generally known as the system class loader. It is responsible for loading the user class path (ClassPath) designated libraries, developers can directly use this class loader, if the application is not too own custom class loader, the general is to use this class loader.

Parent class loader delegation mode (Parents Delegation Model) refers to the addition of the top-level boot class loader, the remaining class loader should typically a parent-child relationship between its parent class loader, class loader will not Inheritance (Inheritantce) relationships to achieve, but use a combination of relations (Composition) to reuse code with the parent loader.
Parent delegation model is working process: If a class loader class loader receives a request, it first does not own to try to load this class, but to delegate this request to the parent class loader to complete all of load request final are transferred to the top of the boot class loader, only the parent loader loading request can not be completed (it does not search classes needed to find), sub-loader will try to load your own.
Such as its Java class loader class together with one kind of relationship with a priority level, such as java.lang.Object, which in rt.jar, no matter which class loader to load this class are ultimately pay start to top class loader to load, so the Object class loader in all environments are the same class.

Destruction parents delegation model

  1. Since JDK1.0 class loader era existed, and parents delegation model was only introduced after JDK1.2, so in order to be compatible made some adjustments.
  2. JNDI example scenario, there is a startup code JNDI class loader, but the interface to call the provider under ClassPath code. Therefore, the introduction of Java thread context class loader (Thread Context ClassLoader). This class loader can be set by setContextClassLoader () method java.lang.Thread class is not set when creating a thread will inherit from the parent thread, if applied globally have not been set, then this is the default application class loader loader. JDNI will use this class loader to load the service's code, so the actual request is the parent child class loader class loader loading the class to complete the action.
  3. The dynamic of the program. Alternatively hot code (HotSwap), hot module deployment (HotDeployment). JSR-291 (OSGi R4.2).

Guess you like

Origin www.cnblogs.com/pluto4596/p/11962428.html