"Understanding JVM" JVM memory model __java Core technology Analysis

Source: Internet
Author: User
Tags constant exception handling instance method modifier xms

The JVM defines the range of data that is used during the execution of several programs. Some of the data in this area is created when the JVM is started and destroyed when the JVM exits. The rest of the data is dependent on each thread, created when the thread is created, and destroyed when the thread exits.


Program Counter

A program counter is a small memory space that can be viewed as the line number indicator of the bytecode executed by the current thread. Basic functions such as branching, looping, jumping, exception handling, and thread recovery need to be relied upon for this counter to complete.

Because the multithreading of Java virtual Machines is achieved through the way in which threads rotate and allocate processor execution time, a processor (a kernel for multi-core processors) executes only the instructions in one thread at any given moment. Therefore, in order to return to the correct execution position after the thread switch, each thread needs to have a separate program counter, the counters between the threads do not affect each other, isolated storage, we call such memory areas as " thread-Private " memory.

If the thread is executing a Java method, this counter records the address of the executing virtual machine bytecode instruction, and if the Natvie method is executing, the counter value is empty (Undefined).

This memory area is the only area that does not specify any outofmemoryerror in the Java Virtual Machine specification.


Virtual Machine Stack

The thread is private, and its lifecycle is the same as the thread. The virtual machine stack describes the memory model that is executed by the Java method: Each method is executed at the same time creating a stack frame (stack frame) to store information such as local variables table, Operation Stack, dynamic link, method exit, and so on .

The animation is produced by the result of a frame-by-frame picture continuous switching result, in fact, the operation of virtual machines and animation is similar, every program running in the virtual machine is also the result of a lot of frame switching, but these frames are stored in the method of local variables, operand stacks, dynamic links, method returns the address and some additional additional information. Each method is invoked until the completion of the process, corresponding to a stack frame in the virtual machine stack from the stack to the process.

For the execution engine, only the stack frame at the top of the stack is valid, called the current stack frame, in the active thread, and the method associated with the stack frame is called the current method . all bytecode directives run by the execution engine operate only against the current stack frame . local Variable Table

A local variable table is a set of variable value storage space that holds the local variables defined within the method parameters and methods . When a Java program is compiled into a class file, the capacity of the maximum local variable table that the method needs to allocate is determined in the Max_locals data item of the method's code attribute.

The capacity of a local variable table is the smallest unit of a variable slot (Slot), and a Slot in a 32-bit virtual machine can hold a data type within 32 bits (Boolean, Byte, char, short, int, float, Reference and ReturnAddress eight species).

The reference type virtual machine specification does not specify its length, but in general, the virtual machine implementation should at least be able to find the object type data in the starting address index and the method area of the object in the Java heap directly or indirectly from this reference.

The ReturnAddress type is a byte-code instruction JSR, Jsr_w, and RET service that points to the address of a byte-code instruction.

The virtual machine uses the local variable table to complete the pass of the parameter value to the parameter variable list , and if it is an instance method (not static), then the slot of the No. 0 bit index of the local variable table defaults to the reference used to pass the instance of the object to which the method belongs, through this access.

Slot is reusable, and when a variable in slot is out of scope, the next time the slot is allocated, the original data will be overwritten. Slot a reference to an object can affect the GC (if referenced, it will not be reclaimed).

the system does not give an initial value to the local variable (both instance and class variables are given an initial value). That is, there is no preparation phase like a class variable. operand Stacks

As with the local variable area, the operand stack is also organized into an array in word length. But unlike the former, it is accessed not by index, but by standard stack operations-stack and stack. For example, if an instruction pushes a value into the operand stack, another command can then eject the value to use later.

Virtual machines store data in the operand stack in the same way as in a local variable: such as int, long, float, double, reference, and ReturnType storage. Values for byte, short, and char types are also converted to int before they are pressed into the operand stack.

The virtual machine takes the operand stack as its workspace--most of the instructions have to eject the data from here, perform the operation, and then press the result back to the operand stack. For example, the Iadd command is going to pop two integers from the operand stack, performs the addition operation, and the result is pressed back into the operand stack, and the following example shows how a virtual machine adds two local variables of type int and then saves the result to a third local variable:

[plain] view plain copy print? Begin ILOAD_0//push the int in local variable 0 ontothe stack iload_1//push "int in" local variable 1 onto The stack iadd//Pop two ints, add them, push result istore_2//pop int, store to local variable 2

In this byte-code sequence, the first two directives iload_0 and iload_1 are placed into the operand stack with integers indexed 0 and 1 in local variables, followed by a iadd instruction that pops the two integers together from the operand stack, and then presses the result into the operand stack. The fourth instruction istore_2 pops the result from the operand stack and stores it in the location where the index of the local variable area is 2. The following figure describes in detail the state change of local variables and operand stacks in this process, and the local variable area and operand stack area not used in the graph are expressed in blank.

Dynamic Connection

When a virtual machine is running, a run-time pool of characters holds a large number of symbolic references that can be viewed as indirect references to each method. If the method representing stack frame A wants to invoke a method that represents the stack frame B, the method call instruction for this virtual machine is used as a parameter in the notation reference of the B method, but because the symbolic reference does not directly point to the memory location that represents the B method, you must also convert the symbolic reference to a direct reference before calling. The real method can then be accessed through a direct reference.

If a symbolic reference is converted to a direct application during class loading or first use, the conversion becomes static and if it is converted to a direct reference during run time, then the conversion becomes a dynamic connection.

return address

The return of the method is divided into two cases, one is the normal exit, after the exit will be based on the definition of the method to determine whether to pass the return value to the upper level of the caller, one is the result of an exception to the end of the method, which does not pass the return value to the upper level

But either way the method ends, when exiting the current method, it jumps to the position where the current method is invoked, and if the method is normally exited, the value of the caller's PC counter can be used as the return address, because the exception exit is determined by the exception handling table.

A call to the method corresponds to the stack frame in the virtual machine stack of a stack of operations, so what you might do when exiting a method includes restoring the local variable table of the upper method and the operand stack, and, if there is a return value, pressing the return value into the operand stack of the caller's stack frame, The value of the PC counter is also adjusted to the next instruction in the method call entry.

Exception

In the Java Virtual Machine specification, there are two exceptions to the virtual machine stack: If the thread requests a stack depth greater than the virtual machine allows, it throws a stackoverflowerror exception; If the virtual machine stack can be dynamically extended (most of the current Java Virtual machines can be dynamically expanded, except that fixed-length virtual machine stacks are also allowed in the Java Virtual Machine specification, and OutOfMemoryError exceptions are thrown when the extension cannot be applied to enough memory.


Local Method Stack

The local method stack (Native methodstacks) plays a very similar role to the virtual machine stack, except that the virtual machine stack performs Java methods (that is, bytecode) services for the virtual machine, while the local method stack is the Native method service that is used by the virtual machine. The language, usage, and data structure of the methods used in the local method stack in the virtual machine specification are not enforced, so the specific virtual machine is free to implement it. Even some virtual machines (such as the Sun HotSpot virtual machine) directly combined the local method stack with the virtual machine stack .

As with virtual machine stacks, the local method stack area also throws Stackoverflowerror and OutOfMemoryError exceptions.


Heap

The heap is the largest chunk of memory managed by the Java Virtual machine. The Java heap is an area of memory that is shared by all threads and is created when the virtual machine is started. The only purpose of this memory area is to hold the object instance, where almost all object instances allocate memory. However, with the development of JIT compiler and the gradual maturation of escape analysis technology, stack allocation, scalar substitution optimization technology will lead to some subtle changes occur, all the objects are distributed on the heap and gradually become less "absolute".

The heap is the main area of garbage collector management and is therefore often referred to as a "GC heap ."

The heap size can be set by the -xms ( minimum) and -xmx(maximum) parameter settings,-XMS the minimum memory requested for the JVM when it is started, default to 1/64 of the operating system's physical memory, but less than the maximum memory that can be requested by the JVM 1g,-xmx. The default is 1/4 of physical memory but less than 1G, and by default when free heap memory is less than 40%, the JVM increases the size specified by heap to-XMX, which can be specified by-xx:minheapfreeration=; When the free heap memory is greater than 70%, The JVM reduces the size of the heap to the size specified by the-XMS, which can be specified by xx:maxheapfreeration=, and for running the system, to avoid frequent resizing of the heap at run time, the-XMS is usually set to the same value as the-XMX.

If from the memory recovery point of view, because now the collector is basically used by the collection algorithm, so the Java heap can also be subdivided into: the new generation and the old age;

New Generation : The newly created objects are all from the Cenozoic allocated memory , the Cenozoic by Eden space and two pieces of the same size Survivorspace ( Often called S0 and S1 or from and to), the size of the new generation can be specified by -xmn parameters, or the size of Eden space and Survivorspace can be adjusted by -xx:survivorration .

old age : used to store after a number of new generation of GC still surviving objects, such as caching objects, newly created objects may be directly into the old age, there are two main situations: 1, large objects, can be set by the start parameter -xx: Pretenuresizethreshold=1024 (in bytes, default 0) to represent more than the Cenozoic distribution, but directly in the old age distribution. 2, large Array object, and no reference to external object in array.

The memory size of the older generation is-xmx corresponding to the value minus the-xmn corresponding value.

If there is no memory completion instance allocation in the heap, and the heap can no longer be extended, the OutOfMemoryError exception is thrown.


Method Area

The method area is inside a JVM instance, and the type information is stored in a memory logical area called a method area. Type information is extracted by the class loader from the class file when the class is loaded. Class (Static) variables are also stored in the method area.

Simply put, the method area is used to store the metadata information for the type, and a. class file is the representation of the class before it is used by the Java Virtual machine, which is loaded, connected (validated, prepared, parsed) and initialized once the class is used. The load (and then the result is transformed from the. class file into a specific data structure in the method area). This data structure will store the following information:

Type Information

Fully qualified name of this type

The fully qualified name of the direct superclass of this type

Whether this type is a class type or an interface type

This type of access modifier

Ordered list of fully qualified names of any direct hyper-interfaces

Field Information

Field name

Field type

Modifier for field

method Information

Method name

Method return type

Number and type of method arguments (in order)

Modifiers for the method

Other Information

All class (static) variables except constants

A pointer to ClassLoader

A pointer to a class object

Chang (constant data and symbolic references to other types)

The JVM maintains a constant pool for each loaded type. A constant pool is an ordered set of constants used by this type, including actual constants (String,integer, and floating point constants) and symbolic references to types, fields, and methods. The data items in the pool, like array items, are accessed through the index .

The metadata for each class, whether it is building an instance of the class or a method that invokes an object of that class, accesses the metadata for the method area.

When building an object, the JVM allocates space to the object in the heap. These spaces are used to store the current object instance properties and the instance properties of their parent classes (which are obtained from the method area), noting that this is not just allocating space for the instance properties of the current object, but also assigning instance properties to the parent class. In fact, we can answer the first question, that is, when instantiating a subclass of a parent class, the JVM also constructs an object of the parent class. This problem can also be verified from another perspective: when invoking the current class's construction method, the constructor method of its parent class is first called until object, and the invocation of the constructor means the creation of the instance, so the parent class is definitely instantiated when the subclass is instantiated.

A class variable is shared by all instances of the class, and you can access it even if there is no class instance. These variables are only related to classes, so in the method area they become a logical part of the class data. Before the JVM uses a class, it must allocate space for each non-final class variable in the method area.

The method area mainly has the following several characteristics:

1, the method area is thread-safe. Because all threads share the method area, data access in the method area must be designed to be thread-safe. For example, if two threads attempt to access the same class in the method area, and the class has not been loaded into the JVM, only one thread is allowed to load it, while the other threads must wait

2, the size of the method area does not have to be fixed, the JVM can be dynamically adjusted according to the application needs. Also, the method area is not necessarily contiguous, and the method area can be freely allocated in a heap (even the JVM's own heap).

3, the method area can also be garbage collection, when a class is not in use (not touch), the JVM will unload this class, garbage collection

You can limit the size of the method area through the -xx:permsize and -xx:maxpermsize parameters.

For developers accustomed to developing and deploying programs on hotspot virtual machines, many people are willing to refer to the method area as a " Permanent Generation " (permanentgeneration), which is inherently not equivalent, simply because hotspot The design team of the virtual machine chooses to extend GC generational collection to the method area, or to implement the method area using a permanent generation. For other virtual machines (such as Bea JRockit, IBM J9, etc.), there is no concept of a permanent generation.

Garbage collection behavior is relatively rare in this region, but not that data enters the method area as "permanent" as the name of the permanent generation. The memory recovery target for this area is primarily for the collection of constant pools and the unloading of types.

The OutOfMemoryError exception is thrown when the method area is unable to meet the memory allocation requirements.


Summary

name

characteristic

function

Configuration Parameters

Exception

Program counter

Small memory footprint, thread-private,

Life cycle is the same as thread

Roughly byte code line number indicator

No

No

Virtual Machine Stack

Thread is private, life cycle is the same as thread, using contiguous memory space

Java method Execution memory model, store local variables table, Operation Stack, dynamic link, method exit and other information

-xss

Stackoverflowerror

OutOfMemoryError

Java heap

Thread sharing, life cycle is the same as the virtual machine, you can not use a contiguous memory address

Save object instances, all object instances (including arrays) are allocated on the heap

-xms

-xsx

-xmn

OutOfMemoryError

Method area

Thread sharing, life cycle is the same as the virtual machine, you can not use a contiguous memory address

Store data such as class information, constants, static variables, just-in-time compiler-compiled code that has been loaded by the virtual machine

-xx:permsize:

16M

-xx:maxpermsize

64M

OutOfMemoryError

Run a constant-amount pool

A part of a method area that is dynamic

Store literal and symbolic references


Direct Memory

Direct memory is not part of a virtual Run-time data area, nor is it a memory area defined in the Java Virtual Machine specification, but this part of memory is also used frequently and can cause outofmemoryerror anomalies to occur, Memory. So we put it here to explain.

In JDK 1.4, a new NiO (Newinput/output) class was introduced, introducing a channel (Channel) and buffer (buffer) I/O, which can be used to directly allocate the heap of memory using the native function library, and then through a storage in the Java The Directbytebuffer object inside the heap operates as a reference to this memory. This can significantly improve performance in some scenarios because it avoids replicating data back and forth in the Java heap and the native heap.


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.