In-depth understanding of Java Virtual Machines Learning Notes 7--java virtual machine class life cycle

Source: Internet
Author: User

C + + and other pure compilation language from the source to the final implementation of the general experience: compile, connect and run three stages, the connection is completed during the compilation, and Java during the compilation is only the Java Virtual machine can recognize the source code class file, Java Virtual machine-to-class file loading, connections are executed at run time, although class loading and connection will occupy the execution time of the program to increase the performance cost, but can give the Java language a high degree of flexibility and extensibility, Java's OSGi for interface programming and classloader mechanisms, as well as thermal deployment, are the features that take advantage of runtime class loading and connectivity, and the life cycle of Java class classes in virtual machines is as follows:

The order in which the five phases are loaded, validated, prepared, initialized, and unloaded is deterministic, and the parsing phase is not necessarily, and in some cases, in order to support the runtime dynamic binding of the Java language, it can also be started after the initialization phase.

(1). Loading:

The Java Virtual machine loads the class file into memory and verifies, transforms, and initializes the data in the class file, resulting in the process of Java types that can be used directly by the virtual machine.

During the load phase, the Java Virtual machine needs to complete the following 3 things:

A. Get a binary byte stream that defines this class by using the fully qualified name of a class.

B. Convert the static storage structure represented by the binary byte stream that defines the class to the run-time data structure of the method area.

C. Generate a Java.lang.Class object representing the class in the Java heap as the access entry for the method area data.

The loading phase is interleaved with the connection phase, the loading phase is not complete, the connection phase may have started, and the actions taken during the loading phase are still part of the connection phase, and the loading and joining phases remain in a fixed order.

(2). Verify:

Validation is the first step in the connection phase to ensure that the information contained in the byte stream of the class file conforms to the requirements of the current virtual machine and does not compromise the security of the virtual machine, and throws a Java.lang.VerifyError exception if the validation fails.

The main tasks in the validation phase are:

A. File format verification: Verify the class file magic number, primary and secondary version, Chang, class file itself, and so on.

B. Metadata validation: The semantic analysis of the information described by the bytecode, including whether there is a parent class, whether it is an abstract class, whether it is an interface, whether it inherits a class that is not allowed to inherit (the final Class), whether the method implements the parent class or interface, and so on.

C. Bytecode verification: Is the most complex verification process, mainly for data flow and control flow analysis, such as guaranteed jump instruction does not jump to the method body outside the bytecode instruction, data type conversion security and effective.

D. Symbolic reference validation: Occurs when a virtual machine converts a symbolic reference to a direct reference (connecting the third stage-parsing phase to a direct reference), the purpose of the symbol reference validation is to ensure that the parsing action is performed properly, and if it cannot be verified by a symbolic reference, The Java.lang.IncompatibleClassChangeError exception is thrown, such as Java.lang.IllegalAccessError, Java.lang.NoSuchFieldError, Java.lang.NoSuchMethodError and so on.

The validation phase is important for a virtual machine, but is not a required phase, and if the code you are running is already being used and validated over and over again, you can turn off most of the validation measures with the-xverify:none parameter to increase the time of the virtual machine.

(3). Prepare:

The prep phase is a phase that formally allocates memory for class variables (static variables, note not instance variables) and sets the initial value of class variables, which are allocated in the method area.

For a generic non-final class variable, such as public static int value = 123, the initial value after the prep phase is 0 (0 value of the data type) instead of 123, and assigning 123 to value is the action taken during the initialization phase.

For final class variables, constants, such as public staticfinal int value = 123, the initial value of the process in the preparation phase is directly 123, and no preparation is required for the zero value.

(4). Parsing:

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 (Symbolicreference): Describes the referenced target in a set of symbols, regardless of the virtual machine memory layout, and the referenced target is not necessarily loaded into the virtual machine memory.

Direct reference (directreference): A pointer to a 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 same symbol reference is not necessarily the same as the direct reference to the translation process on different virtual machines, and if there is a direct reference, the referenced target object must already be loaded into the virtual machine memory.

The parsed action is mainly for the class or interface, field, class method, interface method Four kinds of symbolic reference to parse.

(5). Initialize:

Initialization is the last stage before a class is used, and in the initialization phase the Java Virtual machine really starts executing the Java program code defined in the class.

The Java Virtual Machine specification strictly specifies that there are only four cases in which the class must be initialized immediately:

A. When you encounter new, get a static variable (except for the final constant), assign a value to a static variable, and call a static method, you need to trigger its initialization first if the class has not been initialized.

B. When a reflection call is made to a class using the method of the Java.lang.reflect package (Class.forName (...)), the initialization of the class needs to be triggered first if it is not initialized.

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

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 class first.

The four cases described above are called active references to a class, and other references do not trigger initialization, called a passive reference.

The process of initializing is actually a process of executing the class constructor <clint> method, the characteristics and considerations of the class constructor execution:

1). Class constructor <clint> method is the compiler automatically collects all class variables (static non-final variable) assignment actions and static initialization blocks (static{...}) in the class. The order in which the compilers are collected is determined by the order in which the statements appear in the source file. A static initialization block can only access a class variable defined before it, a class variable defined after it, which is assignable in the preceding static initialization, but cannot be accessed.

2). Class constructors <clint> Methods Unlike instance constructors <init> methods, it does not require an explicit call to the parent class constructor method, which guarantees that the constructor <clinit> method of the parent class has been executed before the subclass constructor method is called.

3). Because the parent class constructor <clint> method is executed first with the subclass constructor, the static initialization block defined in the parent class is preceded by the class variable assignment operation of the child class.

4). Class constructors <clint> methods are not required for classes and interfaces, and if there is no static initialization block in a class and no class variable assignment operation, the compiler can not generate a class constructor <clint> method for that class.

5). You cannot use static initialization blocks in an interface, but you can have class variable assignment operations, so interfaces can generate class constructors <clint> methods as well as classes.

The interface differs from the class:

First, the class constructor <clint> method of the interface is executed without first executing the parent interface's constructor <clint> method, and the parent interface is initialized only if a static variable defined in the parent interface is used.

Second, the implementation class of the interface does not execute the class constructor <clint> method of the interface at initialization time.

6). Java Virtual opportunity to ensure that a class of <clint> method in a multithreaded environment is correctly locked and synchronized, if multiple threads to initialize a class at the same time, there will only be one thread to execute this class of <clint> method, other threads need to block wait, Until the active thread executes the <clint> method is finished.

During the initialization phase, the <init> method of the instance constructor is executed after the class constructor <clint> method is executed, and the instance constructor is executed in the order of the late Father class, the latter subclass, the first member variable, and the subsequent instance construction method.
(6). Use:

When the initialization is complete, the Java Virtual machine can execute the business logic instruction of class, invoke the method logic of the method area through the entry address of the Java.lang.Class object in the heap, and finally store the result of the method through the method return address into the method area or heap.

(7). Uninstall:

When the object is no longer in use, the Java Virtual machine's garbage collector will reclaim the objects in the heap, and the class that is no longer in use in the method area will be unloaded, otherwise the method area (Sun hotspot permanent generation) is out of memory.

The Java Virtual machine specifies that when the class loader instance of the type is loaded with the unreachable state, the The currently loaded type is unloaded. The Boot class loader instance is always reachable state, and types loaded by the startup ClassLoader may never be unloaded, and type unloading is only a performance optimization measure that reduces memory usage, and is specific to the virtual machine implementation, which is transparent to the developer.

The reliable practice of uninstalling a custom loader-loaded class is:

A. Each time a new instance of a particular classloader is created to load a different version of the specified type, in this scenario, it is common to sacrifice caching specific types of ClassLoader instances to bring performance-optimized strategies.

B. For a version that has already been loaded for the specified type, the unreachable state is reached at the appropriate time, and is unload and garbage collected. Each time you finish using a specific instance of the ClassLoader (make sure you don't need to use it again), the display is assigned null, which may be faster to reach the JVM The class loader instance in the specification unreachable state, increasing the chance that a version of a type that is no longer in use will be uninstalled as soon as possible.

(GO) deep understanding Java Virtual Machine Learning Note 7--java virtual machine class life cycle

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.