Java memory area and virtual machine class loading mechanism

Source: Internet
Author: User

One, Java runtime data region

1. Program counter

" Thread-Private " memory, which is a small memory space, can be seen as the line number indicator of the bytecode executed by the current thread. The only area in the Java Virtual Machine specification that does not have a outofmemoryerror condition.

The bytecode interpreter works by changing the value of this counter to select the next byte-code instruction that needs to be executed, such as branching, looping, jumping, exception handling, thread recovery, and other basic functions that rely on this counter to complete.

2. Java Virtual machine stack

Java virtual stack, thread-private , whose life cycle is the same as the thread. Each method creates a stack frame at the same time to store information such as local variable tables, operand stacks, dynamic links, method exits, and so on.

The "stack" is what people call a virtual machine stack, or a local variable table part of a virtual machine stack.

    • The local variable table holds the various basic data types (bloolean,byte,char,short,int,float,long,double) that are known at compile time, object references (reference types, which are not equivalent to the object itself, It may be a reference pointer to the start address of the object, or it may point to a handle representing the object or other location associated with the object, and the ReturnAddress type, which points to the address of a bytecode directive. The amount of memory space required for a local variable table is allocated between compilers, and when entering a method, this method needs to allocate how much local variable space in the frame is fully deterministic and does not change the size of the local variable table while the method is running.
    • A last-in, first-out (last-in-first-out) operand stack, which can also be called an expression stack. The operand stack and the local variable table have the big difference in the access way, the operand stack does not use the access index the way to carry on the data access, but through the standard stack and the stack operation to complete the data access. Each operand stack will have a clear stack depth for storing values, a 32bit value can be stored with a stack depth of one unit, while the stack depth of 2 units can hold a value of 64bit, of course, the size of the operand stack required to be fully determined during the compilation period, and saved in the Code property of the method.

This area has two exceptions:
① if the thread requests a stack depth greater than the virtual allowable depth, the Stackoverflowerror exception will be thrown;
The ② virtual machine stack can be dynamically extended, but when the extension fails to request enough memory, the OutOfMemoryError exception is thrown.

3. Local Method Stack

The local method stack acts like a virtual machine stack, except that the virtual machine stack executes Java methods (that is, bytecode) services for the virtual machine, while the local method stack is the native method service used by the virtual machine, and the thread is private .
Two common requests for the native method are:
① calls some code in the method that is not written in the Java language;
② uses the Java language to manipulate computer hardware directly in the method;
Exceptions: Stackoverflowerror, OutOfMemoryError

4, Java heap

The Java heap is the largest piece of memory managed by a Java virtual machine. Created at virtual machine startup, the only purpose of this memory region is to hold object instances where almost all of the object instances are allocated memory.
The Java heap is the main area of garbage collector management, and therefore also known as the "GC heap";
A OutOfMemoryError exception is thrown if there is no memory completion in the heap for the instance assignment and the heap cannot be extended.

5. Method area

The method area is used to store data such as class information, constants, static variables, instant compiler compiled code, and so on, that have been loaded by the virtual machine.
The OutOfMemoryError exception is thrown when the method area does not meet the memory allocation requirements.

    • Running a constant pool is part of the method area. class file In addition to the class version, fields, methods, interfaces, and other descriptive information, there is also a constant pool, used to store the compilation period generated by the various literal and symbolic references, which will be loaded in the class load into the method area of the run constant pool storage.
    • Another feature of running a constant pool with respect to the class file constants pool is dynamic, and the Java language does not require constants to be generated only at compile time, that is, the content of the constant pool in the class file is not pre-built to enter the method area to run the const pool, and new constants may be put into the pool during run time. This feature is used by developers more than the Intern () method of the String class.

Ii. Creation of objects

1, virtual opportunity to a new command, first check whether the parameters of this directive can be located in the constant pool of a class symbol reference, and check that the symbol reference represents the class has been loaded, resolved and initialized, if not, you must perform the corresponding class loading process.

2. After the class load check passes, the virtual machine allocates memory for the new object. The size of the memory required by an object is fully determined after the class is loaded, and the task of allocating space to an object is equivalent to having a certain size of memory drawn from the Java heap.

3. After the memory allocation is complete, the virtual machine needs to initialize the allocated memory space to 0 values (excluding object headers).

4, the virtual confidential object to make the necessary settings, mainly for the object header settings.

      • Object header:
        • The first part is used to store the runtime data of the object itself, such as hash code, GC generational age, lock status flag, thread-held lock, biased thread ID, biased timestamp, etc. (Mark Word)
        • The second part, a class pointer, is a pointer to his class metadata that the virtual machine uses to determine which class the object is an instance of.

5, from the point of view of the virtual machine, a new object has been produced, but from the perspective of Java query, object creation has just begun--<init> method has not been executed, all fields are still zero.

After executing the new command, the <init> method is followed and the object is initialized as the programmer wishes. Such a real object is completely produced.

Third, the memory layout of the object

The layout of objects stored in memory can be divided into 3 local domains: Object header (header), instance data (Instance), and aligned padding (Padding).

Instance data: Valid information that the object is actually stored, as well as the various types of field content defined in the program code.

Align padding: it is not necessarily there, there is no special meaning, it only plays the role of placeholder.

Iv. Object access and positioning

The object is created to use the object, and our Java program needs to manipulate the concrete objects on the heap through the reference data on the stack. There are two ways to access the current mainstream, using a handle and a direct pointer.

1, if the use of the handle access, then the Java heap will be a block of memory as a handle pool, reference is stored in the object's handle address, and the handle contains the object instance data and the type of the specific address information.

2, if accessed through a direct pointer, the Java heap object layout must consider how to place access to the type of data related information, and reference is stored directly in the object's address. (How Sun hotspot is implemented)

V. Loading mechanism of Virtual machine class

(i), the time of class loading

1. Class life cycle: Classes start from being loaded into the virtual machine memory until the memory is unloaded.

The order of the five 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 is not necessarily.

2. There are only 5 requests for the class to be "initialized" (while loading, validating, and preparing the natural need to start before this):

When ① encounters the 4 bytecode directives of new, gerstatic, putstatic, or invokestatic, if the class has not been initialized, it needs to trigger its initialization first.

For example, when instantiating an object using the New keyword, read or set the static field of a class (except for a static field that has been put into the constant pool at compile time), and when a static method of a class is called.

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

③ 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.

④ when a virtual machine is started, the user needs to specify a main class to execute (including the class of the main () method), and the virtual opportunity initializes the mainstream first.

⑤ when using dynamic language support for JDK1.7.

(b), the process of class loading

The whole process of class loading: Five stages of loading, validating, preparing, parsing, and initializing.

1. Loading

Load is a phase of the class loading process.

① gets the binary byte stream that defines this class through the fully qualified name of a class (implemented by class loading);

② The static storage structure represented by this byte stream into the runtime data structure of the method area;

③ generates a Java.lang.Class object representing this class in memory as a access entry for various data of this class in the method area.

2. Verification

The first step in the connection phase is 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 itself.

Roughly complete 4 stages of inspection actions: file format verification, metadata validation, bytecode verification, symbolic reference validation.

3. Preparation

Allocate memory for variables and set the class variable initial merit stage, the memory used by these variables is allocated in the method area . The first memory allocation at this time consists of only class variables (static modified variables), not instance variables, which are allocated in the Java heap along with the object when the object is instantiated, and secondly, the "initial value" here is usually the 0 value of the data type.

4. Analysis

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: The symbol applies a set of symbols to describe the target being referenced, the symbol can be any form of literal, as long as the use of the non-ambiguous to locate the target, and the virtual machine implementation of the memory layout independent, the reference target is not necessarily and loaded into memory.
      • Direct reference: A direct reference 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. The referenced target must already exist in memory.

Before the 16 bytecode directives used to manipulate symbol references, the symbol references they use are parsed. All virtual machine implementations can determine, as needed, whether a symbolic reference in a constant pool is parsed when the class is loaded, or when a symbolic reference is to be used before parsing it.

Parsing actions are primarily parsed for classes or interfaces, fields, class methods, method types, method handles, and call Point qualifier 7 class symbol references.

5. Initialization

The initialization phase is the last step in the class loading process, in which the rest of the action is completely dominated and controlled by the virtual machine, in addition to the user application being able to participate through the custom class loader during the load phase. In the initialization phase, the Java program code (or bytecode) that is defined in the class is really starting to execute.

In the preparation phase, the variable has already assigned the initial value of the system requirement, and in the initial phase, the initialization phase is the process of executing the class constructor <client> () method based on the subjective plan that the query formulates to initialize the variables and other resources.

In the <client> () method, the static statement block can only access variables defined in the static statement block, defined in the variable after him, in front of the static statement block may be assigned value, but cannot be accessed.

Six, class loader

The ClassLoader is a load action that "gets the fully qualified name of a class to describe the two loaded byte stream that describes this class" during the load phase of class loading.

Mainly divided into the Startup class loader (c + + language implementation, is a part of the virtual machine itself), the extension class loader, the application class loader, the following two types of loaders are implemented by the Java language, independent of the virtual machine outside, and all inherit from the abstract class Java.lang.Loader.

The implementation of its load order is the parent-delegate model, as shown in:

Java memory area and 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.