JVM Advanced features and Practices (i): Java memory area and memory overflow exception __JVM

Source: Internet
Author: User
Tags data structures exception handling static class throwable

Reference: http://oldblog.csdn.net/column/details/16384.html

In "Fortress besieged" in a sentence, "people outside the wall want to go in, the wall inside people think out", use this to describe between Java and C + + This memory dynamic allocation and garbage collection technology surrounded by the "wall" is more appropriate.

For developers engaged in C, C + +, in the area of memory management, they have absolute "rights"-the control of each object and the maintenance of each object's lifecycle. For Java developers, with the help of the virtual machine automatic memory management mechanism, there is no need to pair delete/free code for each new operation, to reduce memory leaks and memory overflows, which are given to the Java Virtual machine for memory control, but for this reason, When related problems occur, it is difficult to troubleshoot errors without knowing that the JVM uses memory rules. This article then records the concepts, roles, service objects, and possible problems of each region of the Java Virtual Machine memory.

This article will be recorded to learn the following knowledge Points: Java Virtual machine Memory partitioning of regional knowledge theory learn the exception code that will be generated by each region. What actions can cause a memory overflow exception

A. Runtime Zone memory

Java virtual machines, when executing Java programs, divide the areas they manage into different data regions, each with its own purpose, time to create and destroy, and some areas that exist with the start of the virtual machine process, while others rely on the lifecycle of the user's thread. The content managed by the Java Virtual machine is divided into the following areas:

1. Program Counter

(1) meaning function

The program counter (Programs Counter Register) is a small memory space that can be viewed as the line number indicator of the bytecode executed by the current thread. In the virtual machine conceptual model, the bytecode interpreter works by changing the value of the counter to select the next byte code instruction that needs to be executed, such as Branch, loop, jump, exception handling, thread recovery and other basic functions that need to rely on the counter.

(2) Counter and multithreading

Because multiple threads of the JVM are switched by thread and assigned processor execution time in any given moment, a processor (a kernel for a multi-core processor) executes only the instructions in one thread. Therefore, in order to return to the correct execution position after the thread switch, each thread needs a separate program counter, the counter between the threads does not affect each other, isolated storage, equivalent to a "thread-private" memory.

(3) Virtual machine specification record (for exceptions)

If the thread is executing a Java method, this counter records the address of the virtual machine byte-code instruction being executed, or the counter is empty (Undefined) if the native method is executed. Note: This memory area is the only area that does not specify any outofmemoryerror in the Java Virtual Machine specification. 2. Java Virtual machine Stack

(1) meaning function

As with program counters, the Java Virtual machine stack (Java Machine Stacks) is also thread-private, and its lifecycle is the same as that of threads. The virtual machine stack describes the memory model that the Java method executes: Each method creates a stack frame to store information such as local variables table, operand stack, dynamic link, method exit, and so on. Each method from the call to the completion of the process, will correspond to a stack frame in the virtual machine stack into the stack to the stack process.

(2) Java memory distinguish misunderstanding

Most people think that Java memory is divided into heap memory (HEAP) and stack memory (stack), which is a misconception that the partitioning of the Java memory area is far more complex than this rough method. This division is widely circulated because most developers focus on the most closely related to the object memory allocation of memory area is the two, the "heap" of knowledge to follow up, where the "stack" refers to the virtual machine stack, or the virtual machine stack in the variable table part.

(3) The local variable table in the virtual machine stack

The Local variables table holds the eight data types (Boolean, Byte, char, short, int, float, long, double) that are known in the compile period. Object reference (reference type, which is not equal to the object itself, may be a pointer to the starting address of the object, or it may point to a handle that represents the object or another location associated with the object) ReturnAddress type (point to the address of a byte-code directive)

64-bit long and double types of data occupy 2 local variable spaces (Slot), and the remaining data types occupy only 1. The memory controls required by a local variable table are allocated during compilation, and when a method is entered, the amount of local variable space that the method needs to allocate in the frame is completely determined, and the size of the local variable table is not changed during the method run.

(4) Virtual machine specification record (for exceptions)

In the Java Virtual Machine specification, two exceptions are specified for this area: if the thread requests a stack depth greater than the virtual machine allows, it throws a Stackoverflowerror exception. If the virtual machine can be dynamically expanded (most Java virtual machines are currently dynamically scalable, except that the Java Virtual Machine specification allows fixed-length virtual machine stacks), the OutOfMemoryError exception is thrown when the extension cannot be applied to enough memory. 3. Local method Stack

(1) meaning function

The local method stack is similar to the virtual machine stack, where the difference is that the virtual machine stack performs Java methods (i.e., bytecode) services for the virtual machine, while the local method stack serves the Native method that the virtual machine uses.

(2) Virtual machine specification record (for exceptions)

The language, methods, and data structures used in the local method stack are not enforced in the virtual machine specification, so a specific virtual machine can implement it. Even some virtual machines (Sun hotspot virtual machines) directly combined the local method stack with the virtual machine stack.

As with virtual machines, the local method stack throws Stackoverflowerror and OutOfMemoryError exceptions. 4. Java Heap

(1) meaning function

For most applications, the Java heap (HEAP) is the largest chunk of memory managed by a Java virtual machine and is a piece 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. Described in the Java Virtual Machine specification: All object instances and arrays are allocated on the heap. However, with the development of JIT compiler and the maturity 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 is not "absolute".

(2) Java Heap and garbage collector

The Java heap is the main area managed by the garbage collector and is therefore called the GC heap (garbage collected Heap). From the point of view of memory recycling, because the collector basically uses the collection algorithm, so the Java heap can be subdivided into: the Cenozoic and the old age. From a memory allocation point of view, a thread-shared Java heap may be divided into multiple thread-private allocation buffers (Tlab:thread local allocation buffer).

However, regardless of the content, no matter what area, the storage is an object instance, further dividing the purpose is to better reclaim memory, or to allocate memory more quickly. This section only learns about the role of memory regions, and details related to the memory allocation strategy for each zone on the Java heap are explained later.

(3) Virtual machine specification record (for exceptions)

According to the Java Virtual Machine specification, the Java heap can be in a physically discontinuous memory, as long as it is logically contiguous, like disk space. When implemented, it can be fixed size or scalable, but the current mainstream virtual machines are implemented in a scalable way (through-XMX and-xms control).

A OutOfMemoryError exception is thrown if there is no memory complete instance allocation in the heap and the heap cannot be extended. 5. Method Area

(1) meaning function

The method area, like the Java heap, is an area of memory shared by individual threads that stores data such as class information, constants, static variables, and Just-in-time compiler-compiled code that have been loaded by the virtual machine. Although the Java Virtual Machine specification describes the method area as a logical part of the heap, it has an alias called Non-heap (not a heap) to differentiate it from the Java heap.

(2) Virtual machine specification record (for exceptions)

The Java Virtual Machine specification has a very loose limit on the method area, and you can choose not to implement garbage collection except for the same amount of memory as the Java heap and the choice of fixed size or extensibility. Garbage collection is relatively rare in this region. The memory recovery target of this area is mainly for the recovery of the constant pool and the unloading of the type, in general, the recovery effect is unsatisfactory, especially the type of uninstall, the conditions are relatively harsh, but this part of the zone recovery is necessary.

According to the Java Virtual Machine specification, a OutOfMemoryError exception is thrown when the method does not meet the memory requirements. 6. Run a constant amount of pool

(1) meaning function

The runtime (Runtime Constant Pool) is part of the method area. class file In addition to the version of the classes, fields, methods, interfaces, and so on, there is also a constant pool (Constant pool Table) that holds the various literal and symbolic references generated by the compilation period, which are stored in the Run-time pool of the class loading the LIFO method area.

(2) Run a constant pool and class file

Java virtual machines have strict rules for each part of the class file (naturally including Chang), and each byte used to store that data must conform to the requirements of the specification before it is recognized, loaded, and executed by the virtual machine. However, for running a regular pool, the Java Virtual Machine specification does not require any details, and the virtual machines implemented by different providers can implement this memory area according to their own needs. In general, however, in addition to preserving the descriptive symbol references in the class file, the direct reference to the translation is also stored in the Run-time pool.

The other important feature of the runtime's constant pool relative to the class file is dynamic, and the Java language does not require constants to be generated by the compiler, which is not the content of the constant pool in the class file that can be used to run the regular pool of the method area. A new constant may also be put into the pool during the run, and the Intern () method used by the developer is more than the string class.

(3) Virtual machine specification record (for exceptions)

The runtime is a part of the method area, naturally subject to the memory limits of the method area, and throws a OutOfMemoryError exception when the constant pool can no longer be applied to memory. 7. Direct Memory

(1) meaning function

Direct memory is not part of the virtual run-time data, nor is it a memory area defined in the Java Virtual Machine specification (Memory). But this part of memory is also frequently used, but may cause outofmemoryerror abnormal appearance.

(3) The exception

The allocation of native direct memory is not limited by the size of the Java heap, but since it is memory, it is limited by the size of the native total memory (including RAM and swap or paging files) and processor addressing space. When the server administrator configures the virtual machine parameters, it sets the-XMX parameter information according to the actual memory, but often ignores direct memory, making the sum of each memory area larger than the physical memory limit (including physical and operating system limits), resulting in a OutOfMemoryError exception when the dynamic extension occurs. two. Practice: reproduce OutOfMemoryError anomalies

In the Java Virtual Machine specification, in addition to the program counters, there is a possibility that oom exceptions occur in other areas of the virtual machine memory, and the purpose of this section is to verify the contents of each run-time zone that is described in the Java Virtual Machine specification by code. When the developer encounters the actual memory overflow, it can judge the area according to the exception information and locate the cause of the error. 1. Java Heap Overflow

Java heap is used to store object instances, as long as the objects are created continuously and the GC roots to the object with a reachable path to prevent the garbage collection mechanism from purging the objects, a memory overflow exception occurs after the number of objects reaches the maximum heap capacity limit.

"Java Heap memory overflow anomaly test"

/**
 * VM args:-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror/public
class Heapoom {

    static class Oomobject {
    } public

    static void Main (string[] args) {
        list<oomobject> List = new arraylist<oomobject> ();

        while (true) {
            list.add (new Oomobject ());}}}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18

Run Result:

    Java.lang.OutOfMemoryError:Java Heap Space 
    dumping heap to java_pid1820.hprof ... 
    Heap dump file created [24787111 bytes in 0.346 secs] 
    Exception in thread "main" Java.lang.OutOfMemoryError:Java Heap MySpace 
1 2 3 4 5

Results Analysis:

The oom exception of Java heap memory is a common memory overflow exception in practical applications. When an exception occurs, the stack message "Java.lang.OutOfMemoryError" further prompts "Java heap space", and the problem is obvious because the number of objects is too large to reach the maximum heap capacity limit. 2. Virtual machine stack and local method stack Overflow

Two exceptions are described in the Java Virtual Machine specification: If the thread requests a stack depth greater than the maximum depth allowed by the virtual machine, the stackoverflowerror throws a OutOfMemoryError if the virtual machine cannot request enough memory space on the expansion stack.

The above two kinds of anomalies are essentially overlapping parts: when the stack space can not continue to allocate, is the memory is too small or used stack space is too large, its essence is only for the same thing two descriptions.

"Virtual machine stack and local method stack Oom test (1th test only)"

/** 
 * If the thread requests a stack depth greater than the maximum depth allowed by the virtual machine, it throws stackoverflowerror 
 * If the virtual machine cannot request enough memory space on the expansion stack, it will throw OutOfMemoryError 
 * VM args:-xss128k/public  
class Javavmstacksof {  

    private int stacklength = 1;  

    public void Stackleak () {  
        stacklength++;  
        Stackleak ();  
    }  

    public static void Main (string[] args) throws Throwable {  
        javavmstacksof oom = new Javavmstacksof ();  
        try {  
            oom.stackleak ();  
        } catch (Throwable e) {  
            System.out.println ("Stack length:" + oom.stacklength); C17/>throw e;  
        }}}  
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 The 25 26

Run Result:

 stack length:2403 Exception in thread "main" Java 

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.