Class loading mechanism for Java Virtual Machine Java Virtual machine

Source: Internet
Author: User

This blog post focuses on the process of loading a class from a Java virtual machine, some of which are referred to in-depth understanding of Java virtual machines. In order to avoid the tedious explanation, in order to let the reader after reading this article can thoroughly understand the class loading process, first of all to see a piece of Java code, we start from an example:

//classloaderprocess.java FileClass Singleton {Private StaticSingleton Singleton =NewSingleton (); Public Static intcount_1; Public Static intCount_2 =0;Static{count_1++;    count_2++; }Private Singleton() {count_1++;    count_2++; } Public StaticSingletongetinstance() {returnSingleton }} Public  class classloaderprocess {        Public Static void Main(string[] args)        {System.out.println (singleton.count_1);    System.out.println (singleton.count_2); }}

Singleton is a singleton pattern of the class, there are two static variables, in the static code block of two static variables do self-increment operation, in the private construction method, the two static variables to do self-increment operation, the final print out the result is how much? Let's say the correct answer is not 2 and 2, but 2 and 1. We take this problem to analyze how a virtual machine loads a class (if the process of loading a class on a virtual machine is already clear, you don't have to look down ~). After reading this article, I believe you will also be in the process of loading classes from the virtual machine to analyze this Java code.

2. The process of a virtual machine load class life cycle of class 2.1


(I've done my best to draw less ugly >_<) represents a life cycle diagram of a class. Class starts from being loaded into the virtual machine's memory, and its entire lifecycle includes: load, connect (validate, prepare, parse), initialize, use, and unload 7 phases, until the memory is unloaded. The order of the 5 phases of loading, validating, preparing, initializing, and unloading is determined, and the load process of the class must begin in this order, and the parsing phase does not have to be: it can in some cases start after the initialization phase, in order to support runtime bindings for the Java language. Here's a look at each of the process of class loading.

2.2 Loading

We know that the program needs to be loaded into memory to execute, and under what circumstances need to start the first phase of the class loading process: Load? There is no mandatory convention in the Java Virtual Machine specification, which can be given to the virtual machine's implementation from the grasp.
During the load phase, the Java Virtual machine needs to complete the following 3 things:

  1. Gets a binary byte stream that defines this class by using the fully qualified name of a class
  2. Convert the static storage structure represented by this byte stream into the run-time data structure of the method area
  3. Generate a Java.lang.Class object representing this class in memory (heap) to encapsulate the data structure of the class in the method area, as the access entry for various data of this class in the method area

It is clear from these three steps that we can use this class to get a variety of data from a class, which is like a mirror that can reflect the information of the class, so we understand why the class is used in reflection.

2.3 Verification

Validation is the first step in the connection phase, which is designed to ensure that the information contained in the byte stream of a class file conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine itself.
Generally we are compiled from Java files generated by the class file, this is no problem, but the class file does not necessarily require the Java source code compiled, you can use a lot of other ways, such as the hexadecimal editor directly written to produce a class file. If the virtual machine does not check the input byte stream and fully trusts it, it may cause the system to crash because of the load of the harmful byte stream, so authentication is an important work of the virtual machine.

2.4 Preparation

Next is the second step of the connection: ready. The prep phase is a phase that formally allocates memory for class variables and sets the initial value of class variables . Here are two concepts to figure out:

  1. Class variable: Static variable that is modified by static.
  2. Initial value: Refers to the "0 value" corresponding to the data type

So in other words, the prep phase allocates memory for static variables and initializes them to a value of 0 . Static code blocks and instance variables are not included, and static blocks are executed at the following initialization stage, and the instance variables are divided into the Java heap as objects are instantiated. For example:

publicstaticint123;

In the prep phase, value is 0, not 123! Of course, if it is a Boolean data, it is false. The 0 value is for a specific type.

2.5 parsing

  The parsing phase is the process by which a virtual machine replaces a symbolic reference in a constant pool with a direct reference , and what is the correlation between this symbolic reference and the direct reference?

  1. Symbol Reference: A set of symbols to describe the referenced target, the symbol can be any form of the literal, as long as the use can be used without ambiguity to locate the target. The symbolic reference is independent of the memory layout implemented by the virtual machine, and the referenced target is not necessarily loaded into memory.
  2. Direct reference: Refers to 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 referenced target must already exist in memory.
2.6 Initialization

The

Initialization is the last step in the class loading process, and in the previous procedure, the rest of the process is completely controlled by the virtual machine itself, in addition to the first step loading stage, when the user can specify a custom ClassLoader to participate. In the initialization phase, the Java program code (or bytecode) that is defined in the class is really starting to execute.
from the above analysis, in the preparation phase, the static variable has been assigned a value, but only the initial value of the system requirements, and in the initialization phase, for the class static variables assigned to the initial value of the program, as well as the execution of static code block of the program .
about the initialization of the class, you can further analyze the point, just say that the initialization stage is to assign the static variables of the class the actual value of the stage, we can also from another angle to express: The initialization phase is the process of executing the class constructor method (note: Not the constructor of the class that we normally call) , the constructor method is <cinit> () method, It is the that is generated by the compiler to automatically collect the assignment of all static variables in a class and the statements in a static code block, so it is also clear why the initialization phase can also be called the process of class constructor method execution.
It is important to note that the order in which the compiler collects is determined by the order in which the statements appear in the program, where static code blocks can only access variables defined before static blocks, variables that are defined after it, and can be assigned values in the preceding static code block, but cannot be accessed. Let's take an example:

publicclass Test {    static {        0//给变量赋值可以正常通过编译        //但是不能访问,这句编译会提示非法向前引用    }    staticint1;

  <cinit>()The method differs from the constructor of the class, it does not need to display the constructor of the calling parent class, the virtual opportunity guarantees that the method <cinit>() of the parent class is executed before the method of the subclass is executed, so the class of the <cinit>() first executed method in the virtual machine <cinit>() is definitely java.lang.Object.
Because the method of the parent class <cinit>() executes first, it means that the static code block defined in the parent class takes precedence over the static variable assignment operation of the subclass, see an example:

//Demo virtual machine <cinit> method execution Process Public  class cinitmethod {    StaticClass parent{ Public Static intA =1;Static{A =2; }           }StaticClass Sub extends Parent { Public Static intB = A; } Public Static void Main(string[] args)    {System.out.println (sub.b); }}

In this program, in the preparation phase, A is assigned to 0,b 0, in the initialization phase, the first method of executing the parent class, <cinit>() so the a=1 is executed, then a=2, then executes the subclass <cinit>() method, executes b=a, so prints out is 2.
The virtual opportunity guarantees that a class's <cinit>() methods are correctly locking and synchronized in a multithreaded environment, and if multiple threads initialize a class at the same time, there will only be one thread that executes the method of the class, <cinit>() and the other threads will need to block the wait until the active thread finishes executing the method.
Here, the loading process of a class is finished, the class-loaded final product is a class object in the heap, encapsulates the data structure of the class within the method area, and provides the Java programmer with an interface to access the data structures within the method area . So programmers can use this class to get the information related to that class.
It is important to note that this class is loaded, it is not related to the object of the class, until now only static variables and static methods of the class can be used, the object of the class needs us to produce, with the object to manipulate the ordinary member variables and methods.
It should be easy to read the Java code at the beginning of the article.

  1. In the preparation phase, the Java Virtual machine assigns singleton to NULL, and count_1 and Count_2 are assigned 0 (Count_2 is assigned to 0 instead of 0 in the program and is the default value of int).
  2. During the initialization phase, the Java virtual machine executes the static code in sequence,
    First instantiate the singleton, execute the code in the construction method, Count_1 and cout_2 into 1;
    Then the static code is executed sequentially, count_1 is not assigned, or 1,count_2 is assigned a value of 0;
    Finally, the code in the static code block is executed, and count_1 and count_2 each increase by 1, so count_1=2,count_2=1.

The analysis is complete.

-Willing to share and progress together!
--My Blog home: http://blog.csdn.net/eson_15

Class loading mechanism for Java Virtual Machine Java Virtual machine

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.