Two face questions with your thorough analysis Java class loading mechanism

In many Java interview, we often see a study on Java class loading mechanism, such as the following this question:

class Grandpa
{
    static
    {
        System.out.println("爷爷在静态代码块");
    }
}    
class Father extends Grandpa
{
    static
    {
        System.out.println("爸爸在静态代码块");
    }
    public static int factor = 25;
    public Father()
    {
        System.out.println("我是爸爸~");
    }
}
class Son extends Father
{
    static 
    {
        System.out.println("儿子在静态代码块");
    }
    public Son()
    {
        System.out.println("我是儿子~");
    }
}
public class InitializationDemo
{
    public static void main(String[] args)
    {
        System.out.println("爸爸的岁数:" + Son.factor);    //入口
    }
}

Please write the final output string.

The correct answer is:

爷爷在静态代码块
爸爸在静态代码块
爸爸的岁数:25

I believe that many students after seeing this topic, expression of the collapse, did not know where to start. Some even met a few times, still can not find the right answers to the idea.

In fact, this study is to face questions your understanding of Java class loading mechanism. If you do not understand Java-loading mechanism, then you can not answer this question purpose. This article, I will explain by a Java class loading mechanism, allowing you to master the method to answer these topics.

Seven stages Java class loading mechanism

When our Java code is compiled, it will generate the corresponding class file. Then we run the java Demo time order, we actually started the class content JVM bytecode virtual machine executes the file. The process JVM bytecode virtual machine execution class can be divided into seven phases: loading, validation, preparation, parsing, initialization, use and uninstall.

load

Here is the official description for most loading process.

Loading phase is the first phase of class loading process. At this stage, the main purpose of the JVM byte code is converted from a respective location (network, disk, etc.) is a binary stream of bytes loaded into memory, then a Class object is created for the corresponding region in the process of the JVM class, the class object of this class is to access a variety of data entry.

In fact, the loading phase one sentence is: the code data is loaded into memory. This process is not for us to Solve this problem directly related to, but this is a process of class loading mechanism, it is necessary to mention.

verification

When finished loading Class JVM bytecode files and creates corresponding Class object in the method area, check the JVM will start byte stream, only to meet the file JVM bytecode JVM specification in order to be properly executed. This verification process can be roughly divided into the following types:

  • JVM specification verification. JVM will check byte stream format file, determine if it meets JVM specification, if the current version of the virtual machine that can be processed. For example: whether the file is 0x cafe bene beginning, major and minor version number, etc. in the current virtual machine processing range.
  • The code check logic. JVM will codes consisting of data flow and control flow verification, to ensure that a fatal error does not occur after operating the JVM byte code file. For example, a method requires incoming parameter of type int, but use it when they passed in a parameter of type String. The method requires a return result of type String, but in the end did not return a result. Code references a class called Apple, but you actually do not define Apple class.

When the code data is loaded into memory, the virtual machine code data will be verified to see if this code is not really write that according to the JVM specification. This process is for us to answer questions there is no direct relationship, but understand the class loading mechanism must be aware of the process.

Ready (important)

Upon the completion of the checksum byte code files, JVM will start to allocate memory and initialize variables for the class. It should be noted that two key points, namely the object memory allocation and the type of initialization.

  • Memory allocation object. The variables in Java "class variables" and "class member variable," two types of "class variable" refers to a modified static variables, and all other types of variables belong to "class member variables." During the preparation phase, JVM only as "class variables" to allocate memory, but does not allocate memory for the "class member variables." "Class member variable" memory allocation need to wait until the initialization phase began.

For example, the following code at the preparatory stage, will only factor attribute to allocate memory without allocating memory for the website properties.

public static int factor = 3;
public String website = "www.cnblogs.com/chanshuyi";
  • Type initialization. During the preparation phase, JVM will allocate memory for class variables and their initialization. But here it refers to the initialization value of zero in the Java language data type of a variable, rather than the value of the user code to initialize.

For example, the following code after the preparation phase, will be the value of the sector 0, instead of three.

public static int sector = 3;

But if a variable is constant (static final to be modified), then the preparation phase, the property will be given to the user desired value. For example, the following code after the preparation stage, the value of the number will be 3, and not 0.

public static final int number = 3;

The reason why static final will be directly copied, and static variables are assigned a value of zero. In fact, we can think about a little want to understand.

The difference between the two statements is a keyword final modification, the other did not. The final keyword in Java behalf unchangeable meaning, meaning that once the value of the number of assignment would not be changed. Since once the assignment will not change, then we must give a start value which gives the user wants, and is therefore final modified class variables will be given the desired value in the preparation phase. Without being modified final class variables, which may change during the initialization phase or operational phase, so it is not necessary in the preparation stage of the value it gives the user wants.

Resolve

After phase by preparing, for the JVM class or interface, fields, methods class, interface method, type method, and the method handle the call site referenced class qualifiers 7 parsing. The main task at this stage is to sign cited in the constant pool replaced with direct references directly in memory.

In fact, at this stage for us is almost transparent, look like.

Initialization (important)

To the initialization phase, the user-defined Java code really started. At this stage, JVM will initialize the class object according to the execution order of statements, in general, when the JVM encounter the following five cases when the triggers initialization:

  • Encounter new, getstatic, putstatic, when invokestatic these four byte code instructions, if the class is not been initialized, you need to trigger its initialization. This generates four instructions of the most common scenario is the Java code: using the new keyword to instantiate an object when reading or setting a static field of a class (the final modification, the result has been placed in a constant pool of static compiler except) when the field, as well as calling a static method of class time.
  • When using java.lang.reflect package approach to reflect the class called, if the class is not been initialized, you need to trigger its initialization.
  • When initializing a class, if you find the parent class has not been initialized, you need to trigger initialization of the parent class.
  • When the virtual machine starts, the user needs to specify a main class to be executed (contains main () method of the class), the virtual machine to initialize this master class.
  • When using JDK1.7 support dynamic languages, if a final example of the analysis result java.lang.invoke.MethodHandle REF_getstatic, REF_putstatic, REF_invokeStatic the method handle, and this handle corresponding to the class the method is not initialized, it is necessary to trigger the its initialization.

See above several conditions you might faint, but it does not matter, no back, knowing look like, when used behind the back of what you can find.

use

When the initialization phase is completed JVM, JVM starts execution of the user program code starts from the inlet methods. This stage can only look.

Uninstall

When the user program code is completed, they began to destroy JVM Class object is created, and finally responsible for running the JVM also exit memory. This stage can only look.

Actual analysis

Understanding of the Java class loading mechanism, let's look at a few examples to test.

class Grandpa
{
    static
    {
        System.out.println("爷爷在静态代码块");
    }
}    
class Father extends Grandpa
{
    static
    {
        System.out.println("爸爸在静态代码块");
    }
    public static int factor = 25;
    public Father()
    {
        System.out.println("我是爸爸~");
    }
}
class Son extends Father
{
    static 
    {
        System.out.println("儿子在静态代码块");
    }
    public Son()
    {
        System.out.println("我是儿子~");
    }
}
public class InitializationDemo
{
    public static void main(String[] args)
    {
        System.out.println("爸爸的岁数:" + Son.factor);    //入口
    }
}

Think about what the final output of the above code?

The final output is:

爷爷在静态代码块
爸爸在静态代码块
爸爸的岁数:25

Maybe someone will ask why there is no output "son in static code block" the string?

This is because the static field, only to directly define the class of this field will be initialized (to perform static code block), and therefore to refer to a static field in the parent class defined by its subclasses, it will only trigger initialization of the parent class without trigger initialize the subclass.

Opposite the above example, we can begin to analyze from the entrance all the way down analysis:

  • First program to the main method herein, the class member variable factor using the normalized output Son class, but the class is not defined Son class member variables. Then go to the parent class, we find the corresponding class member variables in the Father class, then initialize the Father of the trigger.
  • However, according to the first three kinds of five cases we said above initialization, we need to initialize the parent class Father class, that is, to re-initialize the class initialization Grandpa Father classes. So we initialize class output Grandpa: "Grandpa In static code block", then initialization class output Father: "My father in static code block."
  • Finally, after all the parent class initialization is complete, Son class can call the parent class's static variables, so that the output: "My father's age: 25."

Let us look at the example below to see what the output is.

class Grandpa
{
    static
    {
        System.out.println("爷爷在静态代码块");
    }
    public Grandpa() {
        System.out.println("我是爷爷~");
    }
}
class Father extends Grandpa
{
    static
    {
        System.out.println("爸爸在静态代码块");
    }
    public Father()
    {
        System.out.println("我是爸爸~");
    }
}
class Son extends Father
{
    static 
    {
        System.out.println("儿子在静态代码块");
    }
    public Son()
    {
        System.out.println("我是儿子~");
    }
}
public class InitializationDemo
{
    public static void main(String[] args)
    {
        new Son();     //入口
    }
}

The output is:

爷爷在静态代码块
爸爸在静态代码块
儿子在静态代码块
我是爷爷~
我是爸爸~
我是儿子~

Although we are only examples Son of the object, but when the sub-class parent class initialization drive initialization, the output result as shown above.

We carefully analyze the execution flow of the code above:

  • First, we instantiate an inlet where the object Son, Son therefore trigger initialization class, the class will be initialized to drive Father Son, Grandpa initialize class, thereby performing the static code block corresponding class. Therefore output: "Grandpa In static code block", "Dad static code block", "son in the static code block."
  • When the Son class initialization is complete, it will call the class constructor Son, and the Son call the constructor of the class will also drive the Father, Grandpa call the constructor of the class, the final output will be: "I am a grandfather -" "I am a father ~ "," I am the son of ~. "
    Here we give an example of a slightly more complex.

Here we give an example of a slightly more complex.

public class Book {
    public static void main(String[] args)
    {
        staticFunction();
    }
    static Book book = new Book();
    static
    {
        System.out.println("书的静态代码块");
    }
    {
        System.out.println("书的普通代码块");
    }
    Book()
    {
        System.out.println("书的构造方法");
        System.out.println("price=" + price +",amount=" + amount);
    }
    public static void staticFunction(){
        System.out.println("书的静态方法");
    }
    int price = 110;
    static int amount = 112;
}

The output of the above example is:

书的普通代码块
书的构造方法
price=110,amount=0
书的静态代码块
书的静态方法

Here we take a step by step process to analyze the entire execution of the code.

  • In the two examples above, because the class where the main method and no extra code, we have simply ignored the initialization class where the main method. But in this case, the class where the main method there are a lot of code, we can not directly overlooked.
  • When the JVM at the time of the preparation phase, it will allocate and initialize memory for class variables. At this point, our book instance variables are initialized to null, amount variable is initialized to 0.
  • When entering the initialization phase, because the Book method is the entry procedure, according to the fourth of our five cases above mentioned class initialization: When the virtual machine starts, the user needs to specify a main class to be executed (a main ( ) method of that class), the virtual machine to initialize this master class. Book class JVM will initialize.
  • The JVM Book class initialization of the implementation class constructor (in order to collect the class of all static block of code and the class variable assignment statements constitute class constructor), after execution object constructor (first collector member variable assignment, collected Common block, finally collected object constructor, the final composition object constructor).

Book class for which the class constructor can be simply expressed as follows:

static Book book = new Book();
static
{
    System.out.println("书的静态代码块");
}
static int amount = 112;

So first perform static Book book = new Book () ; this statement, this statement has triggered an instance of the class. With different class constructor, Book then performed by the JVM class member variable, and then to collect common code block, the last execution class constructor, which then execute the statement may be expressed as:

int price = 110;
{
    System.out.println("书的普通代码块");
}
Book()
{
    System.out.println("书的构造方法");
    System.out.println("price=" + price +", amount=" + amount);
}

At this price then assigned a value of 110, output: "normal code book block," "constructor book." At a time when price value of 110, while the amount of the assignment is not running, so a zero value is only given in the preparation stage, so after output "price = 110, amount = 0."

After completion when the class is instantiated, JVM proceeds to initialize class constructor:

static Book book = new Book();  //完成类实例化
static
{
    System.out.println("书的静态代码块");
}
static int amount = 112;

That output: "static block of code books", after the value of the amount given to 112.

  • Here, the class initialization has been completed, JVM performs content main method.
    public static void main(String[] args)
    {
    staticFunction();
    }

    That output: "static method of the book."

Analysis Methodology

As can be seen from the above examples, the order of execution of a class analysis probably the following steps:

  • Determining an initial value of the class variable. In the class loading preparation phase, JVM will initialize a value of zero for class variables, class variables this time there will be an initial value of zero. If it is modified final class variables, directly to the initial value will be the user wants.
  • Initialization entry method. After loading into the class initialization phase, the JVM will be the main method to find the entire inlet, thereby initializing the entire class where the main method. When it is desired to initialize a class, it will first initialize the class constructor, after initializing the object constructor.
  • Initialize a class constructor. The first step is to initialize class constructor class initialization, which will collect the class variable assignment order, static code block, the final composition of the class constructor is performed by the JVM.
  • Constructor initializes the object. Object constructor initializes the second portion is performed after completion of the operation class constructor, which is performed in accordance with the assignment becomes a member of the class, code block sequentially general, the object constructor collection code, object constructor final composition, ultimately executed by the JVM .
    If you encounter other types of initialization when initializing the main method where the class, then continue to follow the class constructor initialization order to initialize the object constructor to initialize continue. This repeated cycle, and ultimately returns the class where the main method.

After reading the above analytical, go look at the beginning of that question is not that much easier to do. A lot of things like this, then mastered a certain knowledge and methods, originally difficult things become a lot easier.

Readers welfare

For in the above article I summed up the Internet company java programmers involved in most of face interview questions and answers made the document architecture and free for everyone to share video material (including Dubbo, Redis, Netty, zookeeper, Spring cloud, distributed, high concurrency architecture technical information), hoping to help review your pre-interview and find a good job, but also to save everyone.
Two face questions with your thorough analysis Java class loading mechanism

Free way to receive information: plus qun group: 956 011 797 Click Join now to find free access management ××× sister!

More thematic framework and videos are shown below:

Two face questions with your thorough analysis Java class loading mechanism

Free way to receive information: plus qun group: 956 011 797 Click Join now to find free access management ××× sister!
Two face questions with your thorough analysis Java class loading mechanism

Guess you like

Origin blog.51cto.com/14295088/2404515