In-depth understanding of Java Virtual Machine Note 02:java memory area and memory overflow exception

Source: Internet
Author: User
Tags java se

1. Run-time data area

The Java Virtual machine divides the memory it manages into several different data regions during the execution of a Java program. These areas have their own uses, as well as the time of creation and destruction:

    • Some regions exist with the start of a virtual machine process
    • Some regions are built and destroyed depending on the start and end of the user thread

According to the Java Virtual Machine specification (Java SE version 7), the memory managed by the Java Virtual machine will include the following runtime data regions.

1.1 Program Counters

Program Counter Register is a small amount of memory space, which can be seen as the line number indicator of the byte code executed by the current thread. In the virtual machine concept model (only the conceptual model, the various virtual machines may be implemented in some more efficient way), the bytecode interpreter works by changing the value of this counter to select the next need to execute the bytecode instruction, branch, loop, jump, exception handling, Basic functions such as thread recovery need to rely on this counter to complete.

Because the multithreading of a Java Virtual machine is implemented in a way that threads rotate and allocate processor execution time, at any given moment, a processor (a kernel for a multicore processor) executes only the instructions in one thread. Therefore, in order for the thread to switch back to the correct execution location, each thread needs to have a separate program counter, the counters between the threads do not affect each other, isolated storage, we call this type of memory area is "thread-private" memory.

If the thread is executing a Java method, this counter records the address of the executing virtual machine bytecode instruction, or null (Undefined) If the native method is being executed. This memory area is the only area in the Java Virtual Machine specification that does not stipulate any outofmemoryerror conditions.

1.2 Java Virtual Machine stack

Like the program counter, the Java Virtual machine stack (Java Stacks) is also thread-private, with the same life cycle as the thread. 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 variable tables, operand stacks, dynamic links, method exits, and so on. Each method from the call until the completion of the process, corresponding to a stack frame in the virtual machine stack into the stack of the process.

Java memory is often differentiated into heap memory (heap) and stack memory (stack), which is coarser, and the division of Java memory areas is actually far more complex. The popularity of this partitioning method only shows that most programmers are most concerned about the memory area that is most closely related to object memory allocation. The "heap" in which the author is referred to in the following, and refers to the "stack" is now talking about the virtual machine stack, or the virtual machine stack in the local variable table part.

The local variable table holds the various basic data types (Boolean, Byte, char, short, int, float, long, double), object references (reference types, which are not equivalent to the object itself) that are known at compile time. 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 64-bit length of long and double data takes up 2 local variable space (slots), and the remaining data types occupy only 1. The amount of memory space required for a local variable table is allocated during compilation, and when entering a method, the method needs to allocate much of the 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.

In the Java Virtual Machine specification, there are two exceptions to this area: if the thread requests a stack depth greater than the virtual machine allows, the STACKOVERFLOWERROR exception will be thrown, and if the virtual machine stack can be dynamically extended (most of the current Java virtual machines can be dynamically extended, However, the Java Virtual Machine specification also allows a fixed-length virtual machine stack, which throws a OutOfMemoryError exception if the extension cannot request enough memory.

1.3 Local Method Stack

The local method stack (Native methods stack) is very similar to the virtual machine stack, but the difference between them is 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. The language, usage, and data structures used by methods in the local method stack in the virtual machine specification are not mandatory, so the virtual machine can implement it freely. Even some virtual machines, such as sun hotspot virtual machines, combine the local method stack and the virtual machine stack directly. As with virtual machine stacks, the local method stack area throws Stackoverflowerror and OutOfMemoryError exceptions.

1.4 Java Heap

For most applications, the Java heap (Java heap) is the largest piece of memory managed by a Java virtual machine. The Java heap is a piece of memory that is shared by all threads and created when the virtual machine is started. The only purpose of this area of memory is to hold object instances where almost all of the object instances are allocated memory. This is described in the Java Virtual Machine specification as: All object instances and arrays are allocated on the heap, but with the development of the JIT compiler and the Escape analysis technology matures, stack allocation, scalar replacement optimization technology will lead to some subtle changes occur, all the objects are allocated to the heap and gradually become not so "Absolutely".

The Java heap is the main area of garbage collector management, so many times it is called a "gc Heap" (garbage collected heap, fortunately not translated into a "garbage heap" in the country). From the memory recovery point of view, because the collector is now basically using a generational collection algorithm, so the Java heap can also be subdivided into: the new generation and the old age, the more detailed there is Eden space, from Survivor space, to survivor space. From the memory allocation point of view, the thread-shared Java heap may divide multiple thread-private allocation buffers (thread Local Allocation buffer,tlab). However, regardless of the partition, it is not related to the content, no matter what area, the storage is still an object instance, the purpose of further partitioning is to better reclaim memory, or to allocate memory more quickly. In this chapter, we discuss only the role of memory areas, and the details of the allocation and recycling of each of these areas in the Java heap will be the subject of chapter 3rd.

According to the Java Virtual Machine specification, the Java heap can be in a physically discontinuous memory space, as long as it is logically contiguous, just like our disk space. When implemented, it can be either fixed or extensible, although the current mainstream virtual machines are implemented in a scalable way (via-XMX and-xms control). A OutOfMemoryError exception will be thrown if there is no memory in the heap to complete the instance assignment and the heap can no longer be expanded.

1.5 Method Area

The method area, like the Java heap, is an area of memory shared by each thread that stores data such as class information, constants, static variables, and code compiled by the immediate compiler 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), which should be distinguished from the Java heap.

For developers who are accustomed to developing and deploying programs on a hotspot virtual machine, many people prefer to call the method area the "permanent generation" (Permanent Generation), which is not inherently equivalent. Just because the design team of the hotspot virtual machine chooses to extend the GC collection to the method area, or to use a permanent generation to implement the method area, so that the hotspot garbage collector can manage this part of the memory like the Java heap, eliminating the effort to write memory management code specifically for the method area. For other virtual machines (such as Bea JRockit, IBM J9, etc.) there is no concept of a permanent generation. In principle, how to implement a method area that is part of the virtual machine implementation details, not constrained by the virtual machine specification, but using a permanent generation to implement the method area, is now not a good idea because it is more prone to memory overflow problems (permanent generation of-xx:maxpermsize caps, J9 and JRockit as long as they do not touch the upper limit of the available memory of the process, such as 4GB in 32-bit systems, there is no problem, and very few methods (such as String.intern ()) can cause different performance under different virtual machines for this reason. Therefore, for the hotspot virtual machine, according to the official route map information, now also has abandoned the permanent generation and gradually changed to adopt native memory to achieve the planning of the method area, in the current release of the JDK 1.7 hotspot, The string constant pool that was originally placed in the permanent generation has been moved out.

The Java Virtual Machine specification has a very loose limit on the method area, and you can choose not to implement garbage collection, except that you do not need contiguous memory and can choose a fixed size or extensible, as with the Java heap. The garbage collection behavior is relatively rare in this area, but it is not the data that enters the method area as "permanent" as the name of the permanent generation. The memory recovery target of this area is mainly for the recovery of constant pool and unloading of type, in general, the recovery of this area "performance" is more difficult to be satisfactory, especially the type of unloading, the conditions are very harsh, but this part of the area is really necessary to recover. In the Sun's bug list, several serious bugs have occurred because of a memory leak caused by a low-release hotspot virtual machine that has not been fully reclaimed for this zone.

According to the Java Virtual Machine specification, a OutOfMemoryError exception is thrown when the method area does not meet the memory allocation requirements.

1.6 Running a constant-rate pool

The runtime Constant pool is part of the method area. In addition to descriptive information such as the version, field, method, and interface of the class file, there is also a constant pool (Constant pool Table) that holds the various literal and symbolic references generated during the compilation period, which will be stored in the run-time pool of the class load backward into the method area.

Java virtual machines have strict specifications for each part of the class file (which naturally includes Chang), and each byte is used to store which data must conform to the requirements of the specification to be recognized, loaded, and executed by the virtual machine, but for running a constant pool, the Java Virtual Machine specification does not require any details. Virtual machines implemented by different providers can implement this memory area according to their own needs. However, in general, in addition to saving the symbolic references described in the class file, the translated direct references are also stored in the run-time-constant pool.

Another important feature of running a constant pool relative to a class file's const pool is its dynamic nature, and the Java language does not require constants to be generated only at compile time, which means that the contents of the constant pool in the class file are not pre-placed to enter the method area to run the frequent pool. It is also possible to put new constants into the pool during the run, which is the intern () method of the String class, which is used by developers more.

Since the run-time-constant pool is part of the method area, it is naturally constrained by the memory of the method area, which throws a OutOfMemoryError exception when the constant pool is no longer able to request memory.

1.7 Direct Memory

Direct memory is not part of the data area when the virtual machine is running, nor is it an area of memory defined in the Java VM specification. But this part of the memory is also used frequently, but also may cause outofmemoryerror abnormal appearance, so we put here to explain together.

The new Input/output class was added to JDK 1.4, introducing an I/O approach based on channel and buffer, which can be used to directly allocate out-of-heap memory using the native function library. It then operates as a reference to this memory through a Directbytebuffer object stored in the Java heap. This can significantly improve performance in some scenarios because it avoids copying data back and forth in the Java heap and native heap.

Obviously, the allocation of native direct memory is not limited by the size of the Java heap, but since it is memory, it is bound to be 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, the parameter information such as-XMX is set according to the actual memory, but the direct memory is often ignored, so that the sum of each memory region is greater than the physical memory limit (including physical and operating system-level limitations), resulting in a OutOfMemoryError exception when dynamic scaling occurs.

In-depth understanding of Java Virtual Machine Note 02:java memory area and memory overflow exception

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.