Java temperature to understand the new (10) class loading mechanism

Source: Internet
Author: User

Class loading is the first step in a Java program, and studying the loading of classes can help you understand the JVM execution process and instruct developers to take more effective steps to match the program execution. The second purpose of the research class loading mechanism is to enable the program to dynamically control class loading, such as thermal deployment, to improve the flexibility and adaptability of the program.

1. Class loading mechanism

Let's look at how a virtual machine loads a class file.

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

The life cycle of a class includes load (Loading), validation (verification), preparation (preparation), parsing (Resolution), initialization (initialization), use (using), Unload (unloading) seven phases, where validation, preparation, and parsing of three parts are collectively referred to as the connection (linking). The loading of a class refers to the five stages from load to initialization.

The order of the seven phases, in addition to the parsing and use phases, is determined by the order in which the other phases begin, and must be started in such a sequential manner, but not in order to be completed in such a sequential way, usually in a mixed, cross-cutting process. It is common to invoke or activate another phase during one phase of execution. In some cases, the parsing phase can be started after the initialization phase to support Java Runtime Bindings (RTTI), while the usage phase is performed at different stages by the definition of the contents of the class file.

The virtual machine specification does not enforce constraints on when to load this phase, but for the initialization phase, the virtual machine specification is strictly defined and only four cases must be initialized immediately to the class:

A, when encountering the 4 bytecode instruction of new,getstatic,putstatic or invokestatic, if the class has not been initialized, it needs to trigger its initialization first. The 4 specified scenarios are generated by instantiating an object with the new keyword, reading or setting a static field of a class, and invoking a static method of a class. Of course, static fields that are final decorated and put the results into a constant pool at compile time do not belong to these scenarios, and the values of such static fields are optimized by the compiler at compile time and placed directly into the constant pool, whose references point directly to its entry in the constant pool.

b, when you make a reflection call to a class using the Java.lang.reflect package method, you need to trigger its initialization first if the class has not been initialized.

C, when initializing a class, if it is found that its parent class has not yet been initialized, it is necessary to trigger the initialization of its parent class first.

D, when the virtual machine starts, the user needs to specify a main class to execute (the class that contains the main () method), and the virtual opportunity initializes the main class first.

The behavior in the above four scenarios is called an active reference to a class, except that all references to the class do not trigger initialization, called a passive reference.

The main difference between the loading process of an interface and the class loading process is the 3rd, that is, when an interface is initialized, it is not necessary to initialize its parent interface first, but only when it is actually used in a field in the parent interface.

The following is a brief description of each phase of the class load.

During the load phase, the virtual machine needs to complete three things: obtain a binary byte stream defined by the fully qualified name of a class, and convert the static storage structure represented by this byte stream into the runtime data structure of the method area. A Java.lang.Class object representing this class is generated in the Java heap as the access entry for the data in the method area.

Verification phase, different virtual opportunities for different class verification implementation, but generally complete the following four stages of the inspection process: file format verification (verify that the byte stream conforms to the class file format specification, and can be processed by the current version of the virtual machine), metadata validation (byte code description information for semantic analysis, Ensure that the description information conforms to the Java language Specification), bytecode verification (data flow and control flow analysis of the class method body, ensure that the class's methods do not compromise the behavior of the virtual machine at runtime), and symbolic reference validation (occurs during the parsing phase when a symbolic reference is converted to a direct reference).

The preparation stage, formally as a class member variable (note that it is not an instance member variable, the instance variable is allocated on the Java heap as the object is instantiated), allocates memory and sets the class variable initial value (typically a 0 value of the data type, without an assignment operation) that will be allocated in the method area.

Example: public static int value=123; After the prep phase, the initial value of value is 0 instead of 123, and the assignment instruction is executed through the constructor method during the initialization phase.

During the parsing phase, the virtual machine replaces the symbolic reference within the constant pool with the process of direct referencing. A symbolic reference is independent of the memory layout, and the target of a direct reference must already exist in memory. Parsing actions are mainly for classes or interfaces, fields, class methods, interface methods, and four types of symbolic references.

During the initialization phase, it is the process of executing the class constructor <clinit> () method to actually start executing the Java program code (bytecode) defined in the class.

Some features of the <clinit> () method:

The <clinit> () 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{}), 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.

The <clinit> () method differs from the constructor of the class (or the instance constructor <init> () method), and it does not need to explicitly call the parent class constructor, which completes the parent class before the subclass's <clinit> () method executes < The execution of the Clinit> () method.

Because the <clinit> () method of the parent class executes first, it means that the static statement block defined in the parent class takes precedence over the child class's variable assignment operation

The <clinit> () method is not necessary for a class or interface, and if there is no static statement block in a class and no assignment to the variable, the compiler can not generate the <clinit> () method for the class.

A static statement block cannot be used in an interface, but there are still assignment operations for variable initialization, so the interface will generate the <clinit> () method as the class does, unlike where the class is executing the <clinit> () method of the interface 坱 the parent class is executed first <clinit > () method.

The virtual opportunity guarantees that a class <clinit> () method is properly locked and synchronized in a multithreaded environment, and if multiple threads initialize a class at the same time, only one thread executes the <clinit> () method of the class, and the other threads block the wait. Until the active thread executes the <clinit> () method is complete.

Having learned the stages of each class loading mechanism, we need to learn more about the concept of ClassLoader. The class loader is used only to implement the load action of a class, that is, to obtain a binary byte stream that describes this class through the fully qualified name of a class. But for a class, to determine whether two classes are equal (instanceof,equal), the premise is that two classes are loaded by the same classloader, otherwise, whether two classes from the same class file, the two classes are necessarily unequal, that is, for any class, Need to establish its uniqueness in the Java Virtual machine, together with the class loader that loads it and the class itself.

In the JAVA developer's view, the ClassLoader can be divided into the following three types of system-provided ClassLoader: Start the ClassLoader (Boostrap ClassLoader, which is responsible for loading the class library stored in the <java_home>\lib directory into the virtual machine memory. It cannot be referenced directly by a JAVA program), the extension ClassLoader (Extension ClassLoader, implemented by Sun.misc.launcher$extclassloader, is responsible for loading <java_home>\lib\ The class library in the Ext directory can be used directly by the developer, and the Application class loader (implemented by Sun.misc.launcher$appclassloader, is responsible for loading the class library specified on the user classpath (ClassPath), which can be used directly by the developer. and is the default class loader).

The parents delegation model is used in Java to implement the load pattern of a class. The parental delegation model requires that, in addition to the top-level startup ClassLoader, the rest of the ClassLoader should have their own parent ClassLoader, where the parent-child relationship is not implemented with inheritance, but instead uses a combination to take advantage of the parents loader.

Parent delegation Model work process: If a class loader receives a request for a class load, it first does not attempt to load the class itself, but instead delegates the request to the parent class loader, which is the case for each level of the ClassLoader, so all load requests should eventually be routed to the top-level startup class loader. The child loader does not load itself until the parent loader feedback that it is unable to complete the load request (its search scope does not find the desired class). The model is as follows:

2. Loading order of Classes

Class loading is divided into six steps:

(1) When an object of type dog is first created, or when the static method of the dog class is first accessed by the/static field, the Java interpreter must find Dog.class (search in the pre-set classpath).
(2) After Dog.class is found (it will create a class object, which will be learned later), all of its static initialization modules will run. Therefore, static initialization occurs only once-when the class object is first loaded.
(3) When creating a new dog (), the build process of the dog object will first allocate enough storage space for a dog object in the heap.
(4) This storage space is cleared to zero, and all the basic types in dog are set to their default values (0 for numbers, and for Boolean and char equivalent settings).
(5) All initialization occurs when the field definition is performed.
(6) Executes the builder.

Let's talk about the understanding of each step:

The first step:

This sentence describes when and how a class is loaded by the JVM. Obviously, according to this statement, we can see that when an object is first created with the New keyword, or when a static class method or class field is accessed directly, the JVM starts to load a class (the class here is the dog class, and the next version is strongly required to change to duck! )。 The JVM then finds the class file with the same name by default or by the user's own set of Classpath, and then the load occurs.

Step Two:

The result of loading is a class object in the JVM that contains all the information for that class. The static module is initialized shortly thereafter. Here is to say that all you do about static module initialization work is here the first and last time-whether you use the "static int duck = 250" form, or the form of a static block of code.

Ps:

Static code block initialization

Static int Duck; Static  =;}

Third to fourth step:

These two words are the remarks of the first two sentences: 1. In Java, objects are generated in heap memory. 2. And after allocating memory for this object, each storage unit in this memory will be cleared by the JVM by 0 (the effect is that the base type is set to 0 or 0.0 or false, and the reference is set to null)

To be reminded, the actions in both sentences are completed before one or two sentences. Otherwise, there will be a ridiculous situation: no matter how you initialize, you will end up depressed the discovery is zeroed.

Fifth Step:

This sentence is the least nutritious, is an emphasis.

Sixth step:

In the initialization of inheritance, when you invoke a subclass of a parent class, perhaps it is called the constructor of this subclass, the JVM always calls the constructor of the parent class for full initialization. That is, calling this subclass, the JVM will regularly find his parent class. If the parent class is also a subclass of a parent class, the JVM will continue to look up the parent class until the final parent class--object the class. Then, in turn, the construction method of each parent class is called to initialize its immediate subclass-until the end of the child class. In this way, the initialization of any module will not fall.

Java temperature to understand the new (10) class loading mechanism

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.