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

Source: Internet
Author: User

[TOC]

Overview

The virtual machine loads the data of the description class from the class file into the memory, verifies the data, parses and initializes it, and finally forms the Java type that can be used directly by the virtual machine, which is the class loading mechanism of the virtual machine.

Dynamic loading and dynamic connection

In the Java language, the loading, connection, and initialization of types are done during program runs.

The life cycle of class loading time classes

Class starts from being loaded into the virtual machine's memory and unloads out of memory location, and its entire lifecycle includes: load (Loading), validate (verification), prepare (Preparing), Parse (Resolution), Initialize ( initialization), use (using), and unload (unloading) 7 stages. Where validation, preparation, parsing 3 parts collectively referred to as the connection (linking).

Passive reference Example one (calling a subclass inherits a field from the parent class)

Look at the following code:

class SuperClass {    static {        System.out.println("super class !!!");    }    publicstaticint100;}classextends SuperClass {    static {        System.out.println("sub class !!!");    }}publicclass Main {    publicstaticvoidmain(String[] args) {        System.out.println(SubClass.value);    }}

Output:

superclass !!!100

For a static field, only the class that directly defines the field is initialized, so referencing the static field defined in the parent class through its subclasses will only trigger the initialization of the parent class without triggering the initialization of the subclass.

Example two (array)
publicclass Main {    publicstaticvoidmain(String[] args) {        new SuperClass[10];    }}

Not output super class !!! .

There is no SuperClass initialization phase of the triggering class, but the [LSuperClass initialization phase of the class that triggered it.

Example three (static constant)
class ConstClass {    static {        System.out.println("ConstClass");    }    publicstaticfinal"hello";}publicclass Main {    publicstaticvoidmain(String[] args) {        System.out.println(ConstClass.S);    }}

Output

hello

Although the Java source code in the Constclass class to reference the constant s, but in fact, in the compilation phase through constant propagation optimization , the value of this constant has been stored in the main class of the constant pool , The reference to the constant CONSTCLASS.S is actually converted to the main class's reference to its own constant pool. That is, in fact, the class file of main does not have the constclass of the symbol reference entry.

Class-Loaded process loading

During the load phase, the virtual machine accomplishes the following three things:

    1. A binary byte stream that defines this class is obtained through the fully qualified name of a class.
    2. Converts the static storage structure represented by this byte stream into the run-time data structure of the method area.
    3. A Java.lang.Class object representing this class is generated in memory as a access entry for various data of this class in the method area.

The load phase can be done with the system-provided boot class loader, or by a user-defined ClassLoader.

The array class itself is not created by the class loader and is created directly by the Java Virtual machine. However, the element type of the array class (the type after which all dimensions are removed) is ultimately created by the ClassLoader.

Verify

The validation phase will roughly complete the following four phases of validation: file format validation, metadata validation, bytecode validation, and symbolic reference validation.

    1. File Format verification: The main purpose is to ensure that the input byte stream can be correctly parsed and stored in the method area, in a format that describes a Java type of information requirements. The validation of this phase is based on the binary byte stream , which is only validated by this phase and the byte stream is stored in the method area of the memory.
    2. Meta-data validation: The main purpose is to check the metadata information of the class to ensure that there is no metadata information that does not conform to the Java language specification.
    3. Bytecode verification: The main purpose is to determine the program semantics through data flow and control flow analysis, which is legal and logical. The method of ensuring that the class is checked does not make an event that endangers the security of the virtual machine at run time. JDK1.6 is optimized by adding attributes (stacks) to the property sheet of the method body Code property StackMapTable .
    4. Symbol Reference Validation: The purpose is to ensure that the parsing action is performed properly.
Get ready

The prep phase is a phase that formally allocates memory for class variables (Static-modified variables, excluding instance variables) and sets the initial value of class variables, and the memory used by these variables is allocated in the method area .

publicstaticint233;

The value initial value of a variable after the preparation phase is 0 instead of 233, when no method has been started, and the value assignment is compiled, so the assignment will not be executed until the initialization stage .

If it becomes

publicstaticfinalint233;

Then the prepare stage variable value is initialized to the value 233 specified by the Constantvalue property in the field property sheet of the class field .

Analytical

The parsing phase is the process by which a virtual machine replaces a symbolic reference within a constant pool with a direct reference .

Symbol reference

A symbol reference describes the target in a set of symbols, which can be any form of literal , as long as it can be used without ambiguity to locate the target. Regardless of the memory layout implemented by the virtual machine, the referenced target is not necessarily loaded into memory. The literal form of a symbol reference is explicitly defined in the Java Virtual Machine specification's class file format.

Direct reference

A direct reference can be a pointer to a target directly, a relative offset, or a handle that can be indirectly anchored to the target. Related to the memory layout implemented by the virtual machine, if there is a direct reference, then the reference target must exist in memory .

Initialization

Class initialization is the last step in the class loading process and is a step in actually starting to execute the Java program code (or bytecode) defined in the class .

The initialization phase is the process of executing a class constructor <clinit>() method .

    • <clinit>()The method is generated by the combination of the assignment action of all class variables in the compiler's auto-collection class and the statements in the static statement block (static{} block), which are determined by the order in which the statements appear in the source file. A static statement block can only access variables that are defined before a static statement block, and variables that are defined at a later value are assignable and inaccessible .
    • The virtual opportunity guarantees that the methods of the <clinit>() parent class have been executed before the method of the subclass is executed <clinit>() . The first class that executes in a virtual machine <clinit>() must be the object class.
    • Not every class has a <clinit>() method.
    • The method that executes the interface <clinit>() does not need to execute the parent interface's <clinit>() method first. The parent interface is initialized only if the variables defined in the parent interface are used. An interface implements a method that does not execute an interface when the class is initialized <clinit>() .
    • Virtual machines ensure that a class <clinit>() method is correctly locking and synchronized in a multithreaded environment.
Class Loader

A code module that implements the "fully qualified name of a class to obtain a binary byte stream describing this class" is called the ClassLoader.

Class and Class loader

For any class, it is necessary to establish its uniqueness in the Java Virtual machine, together with the class loader that loads it, and the class itself, each with a separate class namespace. (class loader differs, two classes must be unequal)

Parental delegation Model

From the JVM perspective, there are only two different classloader: the first is to start the ClassLoader , which is part of the virtual machine using C + + implementation. The second is all other ClassLoader , implemented by Java, independent of the virtual machine and inherited from the abstract class java.lang.ClassLoader .

Launch class loader (Bootstrap ClassLoader)

The class library that will be stored in <JAVA_HOME>\lib the directory, or -Xbootclasspath in the path specified by the parameter, is loaded into the virtual machine memory.

Extension class loader (Extension ClassLoader)

The sun.misc.Launcher$ExtClassLoader implementation is responsible for loading all class libraries in the <JAVA_HOME>\lib\ext directory, or in the java.ext.dirs path specified by the system variables .

Application class loader (application ClassLoader)

Also known as the System class loader . by sun.misc.Launcher$AppClassLoader implementation, the user class path (ClassPath) is responsible for locking the specified class library. In general this is the default class loader in the program.

The diagram shows a hierarchical relationship between ClassLoader, called the class loader's parental delegation model .

Work process

A class loader receives a class load request, which first delegates the request to the parent ClassLoader to complete, and so is the class loader for each level, so all load requests are eventually routed to the top-level startup ClassLoader. The child loader tries to load itself only when the parent loader has feedback that it cannot complete the load request (its search scope does not find the desired class).

Advantages

The Java class has a hierarchical relationship with precedence as its classloader. For example java.lang.object , regardless of which classloader loads the class and ultimately delegates to the startup ClassLoader for loading, the object class is the same class in the various ClassLoader environments of the program. If no parent delegation model is loaded by each classloader, the system will appear with several different object classes.

Realize

The code is set in the java.lang.ClassLoader的loadClass() method.

protectedClass<?>LoadClass(String name,BooleanResolvethrowsclassnotfoundexception {synchronized(Getclassloadinglock(name)) {//First, check if the class has already been loadedclass<?> C =Findloadedclass(name);if(c = =NULL) {LongT0 = System.Nanotime();Try{if(Parent! =NULL) {c = parent.LoadClass(Name,false); }Else{c =Findbootstrapclassornull(name); }            }Catch(ClassNotFoundException e) {//ClassNotFoundException thrown if class not found                //From the Non-null parent class loader}if(c = =NULL) {//If still not found, then invoke Findclass in order                //To find the class.                LongT1 = System.Nanotime(); c =Findclass(name);//Specify your own class-loading implementation                //This is the defining class loader; record the statsSun.Misc.PerfCounter.Getparentdelegationtime().Addtime(T1-T0); Sun.Misc.PerfCounter.Getfindclasstime().Addelapsedtimefrom(t1); Sun.Misc.PerfCounter.getfindclasses().Increment(); }        }if(resolve) {Resolveclass(c);//class connection Operation}returnC }}

Logic: First check whether it has been loaded, if not loaded, call the parent loader's loadClass() method, and if the parent loader is empty, use the Startup class loader as the parent loader by default. If the parent loader fails to load, throws ClassNotFoundException an exception, and then calls its own findClass() method to load.

In-depth understanding of Java Virtual Machine notes-Virtual machine 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.