Java memory zone and Virtual Machine class loading mechanism, Java Virtual Machine

Source: Internet
Author: User

Java memory zone and Virtual Machine class loading mechanism, Java Virtual Machine

I. Data Area During Java Runtime

1. Program counters

"Thread privateMemory is a small memory space, which can be seen as the row number indicator of the bytecode executed by the current thread. The only region in the Java Virtual Machine specification that has no OutOfMemoryError.

When the bytecode interpreter is working, it means to change the value of this counter to select the next bytecode instruction to be executed, this counter is required for basic functions such as branch, loop, jump, exception handling, and thread recovery.

2. Java Virtual Machine Stack

Java virtual stack,Thread privateIt has the same lifecycle as the thread. When each method is executed, a stack frame is created to store information such as the local variable table, operand stack, dynamic link, and method exit.

The so-called "stack" refers to the Virtual Machine stack, or the local variable table part of the Virtual Machine stack.

  • The local variable table stores various basic data types (bloolean, byte, char, short, int, float, long, and double) known during the compilation period, and object references (reference type, it is not the same as the object itself. It may be a reference pointer pointing to the starting address of the object, or it may point to a handle representing the object or other locations related to the object) and returnAddress (pointing to the address of a bytecode instruction ). The memory space required by the local variable table is allocated between compilers. when you enter a method, the size of the local variable space allocated in the frame is completely determined, the table size of local variables is not changed during method running.
  • An operand Stack of Last-In-First-Out can also be called an Expression Stack ). The access methods of the operand stack and the local variable table are quite different. The operand stack does not use the access index method for data access, instead, a data access is completed through standard inbound and outbound operations. Each operand Stack has a clear stack depth used to store values. A 32bit value can be stored in a unit of stack depth, the stack depth of two units can save a 64-bit value. Of course, the size of the stack required by the operations can be completely determined during the compilation period, and save it in the Code attribute of the method.

There are two exceptions in this region:
① If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, an StackOverflowError exception will be thrown;
② The Virtual Machine stack can be dynamically expanded, but it cannot be applied for enough memory during expansion, and an OutOfMemoryError exception will be thrown.

3. Local method Stack

The role of the local method stack is similar to that of the Virtual Machine stack. The difference is that the virtual machine stack executes the java method (also known as bytecode) service for the virtual machine, and the local method stack serves the Native method used by the virtual machine,Thread private.
Two common requests of the Native method:
① Call some code not written in java in the method;
② Use java to directly operate computer hardware in the method;
Exception: StackOverflowError and OutOfMemoryError

4. Java Heap)

Java heap is the largest memory managed by Java virtual machines. Created when the VM is started, the only purpose of this memory area is to store the object instance, where almost all object instances are allocated memory.
Java heap is the main area for managing the Garbage Collector. Therefore, it is also called "GC Heap ";
If the heap does not have memory for instance allocation and the heap cannot be extended, an OutOfMemoryError will be thrown.

5. Method Area

The method area is used to store data such as class information, constants, static variables, and Code Compiled by the real-time compiler loaded by virtual machines.
When the method area cannot meet the memory allocation requirements, an OutOfMemoryError error is thrown.

  • The runtime constant pool is part of the method area. In addition to the description information such as the version, field, method, and interface of the Class, the Class file also contains a constant pool, which is used to store various literal quantities and symbol references generated during compilation, this part of content will be stored in the runtime pool of the method area after the class is loaded.
  • Compared with the constant pool of Class files, the runtime constant pool is dynamic. Java does not require constants to be generated only during compilation, that is to say, it is not the content of the constant pool preset into the Class file that can enter the constant pool for running in the method area. During running, new constants may also be placed in the pool, the intern () method of the String class is used by developers.

Ii. Object Creation

1. When the VM encounters a new command, first check whether the parameter of this command can locate a Class symbol reference in the constant pool, check whether the class referenced by this symbol has been loaded, parsed, and initialized. If not, the corresponding class loading process must be executed.

2. After the class loading check is passed, the VM allocates memory for the new object. The size of the memory required by the object can be completely determined after the class is loaded. The task of allocating space for the object is equivalent to dividing a fixed size memory from the Java heap.

3. After the memory is allocated, the virtual machine needs to initialize the allocated memory space to a zero value (excluding the object header ).

4. the VM must set the object, mainly for object header settings.

    • Object Header:
      • The first part is used to store the data in the running hours of the object, such as the hash code, GC generational age, lock status mark, lock held by the thread, biased thread ID, and time stamp. (Mark Word)
      • The second part is the class pointer, that is, the pointer to the class metadata of the object. The VM uses this pointer to determine the class instance of the object.

5. From the perspective of virtual machines, a new object has been generated, but from the perspective of Java query, object creation has just started -- <init> the method has not been executed yet, all fields are zero.

After the new command is executed, the <init> method is executed to initialize the object according to the programmer's wishes. Such a real object is generated completely.

3. Object Memory Layout

The layout of objects stored in the memory can be divided into three local areas: object Header, Instance Data, and Padding ).

Instance data: valid information that objects actually store. It is also the content of various types of fields defined in the program code.

Alignment filling: it does not exist and has no special meaning. It only acts as a placeholder.

Iv. Access and positioning of Objects

Objects are created to use objects. Our Java program uses reference data on the stack to operate specific objects on the stack. Currently, there are two mainstream access methods: handle and direct pointer.

1. If a handle is used for access, a block of memory will be allocated in the Java heap as the handle pool. The handle address of the object is stored in the reference, the handle contains the specific address information of the object instance data and type.

2. If you access the object through a direct pointer, you must consider how to place information related to access type data in the layout of the Java heap object. The object address is stored in reference. (Sun HotSpot implementation)

 

V. Virtual Machine Loading Mechanism

(1) Timing of class loading

1. lifecycle of a class: the class starts from being loaded into the memory of the VM and ends when the memory is detached.

 

In the figure, the order of loading, verification, preparation, initialization, and uninstallation is determined. The loading process of classes must start step by step, while the parsing stage is not necessarily.

2. There are only five types of requests that require "initialization" (loading, verification, and preparation must start before) for the class immediately:

① In case of four bytecode commands, new, gerstatic, putstatic, or invokestatic, class initialization must be triggered first if the class has not been initialized.

For example, when you use the new keyword to instantiate an object, read or set a static field of a class (except for static fields that have been modified by final and put results into the constant pool during compilation, and when calling a static method of a class.

② When using the java. lang. reflect package method to call the class for reflection, if the class has not been initialized, it needs to be triggered first.

③ When initializing a class, if you find that the parent class has not been initialized, you must first trigger the initialization of the parent class.

④ When a virtual machine is started, you need to specify a main class to be executed (including the class of the main () method). The virtual opportunity first initializes this mainstream class.

⑤ When JDK1.7 is supported in dynamic languages.

(2) class loading process

The whole process of class loading: Loading, verification, preparation, parsing, and initialization.

1. Load

"Loading" is a stage of the "class loading" process.

① Get the binary byte stream that defines this class through the full qualified name of a class (implemented through class loading );

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

③ Generate a java. lang. Class Object that represents this Class in the memory, and serve as the access portal for various data of this Class in the method area.

2. Verification

The first step of the connection phase is to ensure that the information contained in the byte stream of the Class file meets the requirements of the current virtual machine and does not endanger the security of the virtual machine itself.

Roughly four phases of verification are completed: File Format verification, metadata verification, bytecode verification, and symbol reference verification.

3. Preparation

Officially allocate memory for the variables and set the class variable Initial Value stage. The memory used by these variables isMethod Area. First, only class variables (static modified variables) are included in the memory allocation, but instance variables are not included, instance variables will be allocated to the Java heap when the object is instantiated. Next, the "Initial Value" is usually the zero value of the data type.

4. Analysis

In the parsing phase, the virtual machine replaces the symbol reference in the constant pool with the direct reference.

    • Symbol reference: a symbol is used to describe the referenced object with a set of symbols. A symbol can be a literal in any form and can be positioned to the object without ambiguity, it has nothing to do with the memory layout implemented by the virtual machine. The referenced destination is not necessarily loaded into the memory.
    • Direct reference: direct reference can direct to the target pointer, relative offset, or a handle that can indirectly locate the target. Direct reference is related to the memory layout implemented by virtual machines. The referenced target must already exist in the memory.

Parse the symbolic references that are used before 16 bytecode commands are used for operating symbol reference. All Virtual Machine implementations can determine whether to parse the symbol reference in the constant pool when the class is loaded by the loader as needed, it will not be parsed until a symbolic reference is used.

The parsing action is mainly used for parsing class or interface, field, class method, method type, method handle, and call point qualifier Class 7 symbol reference.

5. Initialization

The initialization stage is the last step in the class loading process. In the previous class loading process, in addition to the user's application can participate in the loading stage through the custom class loader, other actions are completely dominated and controlled by virtual machines. At the initialization stage, the Java program code (or bytecode) defined in the execution class is actually started ).

In the preparation stage, the variable has been assigned an initial value required by the system. In the initial stage, the investigator initializes the variable and other resources based on the subjective plan formulated by the query. In other words, the initialization phase is the process of executing the class constructor <client> () method.

In the <client> () method, the static statement block can only access the variables defined before the static statement block, and the variables defined after it can be assigned values in the previous static statement block, but cannot be accessed.

Vi. class loaders

A Class Loader is a loading action that describes the binary loading byte stream of a class by using the full-qualified name of a class during the loading phase.

Mainly divided into the start class loader (C ++ language implementation, is part of the virtual machine itself), extended class loader, application class loader, the following two types of loaders are implemented in Java language and are independent of the Virtual Machine and inherited from the abstract class java. lang. loader.

The implementation of the load sequence is the dual-parent Delegation Model, as shown in:

 

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.