2.java memory area and memory overflow exception

Source: Internet
Author: User


2.1: Overview

for engaging in C,the developer of C+ + program development, the new memory area of the object and the destruction memory Area (new and delete) are manually called by the programmer. the memory management of Java is performed automatically by the virtual machine. In the event of a memory leak and overflow problem, if you do not understand how the virtual machine uses memory, troubleshooting errors can be an extremely difficult task.

2.2:. data region at run time

650) this.width=650; "Src=" https://s4.51cto.com/wyfs02/M02/9D/F4/wKioL1mJVHPi4uf3AAFQ67j-Bas790.png-wh_500x0-wm_ 3-wmp_4-s_3943279678.png "title=" image 1.png "alt=" Wkiol1mjvhpi4uf3aafq67j-bas790.png-wh_50 "/>

Program Counter (program Counter Register) is a small memory space that can be seen as the line number indicator of the bytecode executed by the current thread. 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 "thread-private" memory

Java Virtual machine stack (Java Virtual machine 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.

Local Method Stack The Native method 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. 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.

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 stipulates that 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.

method area ( M ethod area), like the Java heap, is a region 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. 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. (The Intern () method of the String class).

Direct Memory : Direct Memoryis not part of the data area when the virtual machine is running, nor is it a memory area defined in the Java VM specification

Thread sharing Zone: Heap, method Area (also known as permanent generation)

the next point is the hotspot virtual machine

2.3. Object creation Process

User user = new user ();

The first step: Check that the parameter of this directive is able to navigate to the symbolic reference of a class in the constant pool, and check that the symbol reference represents the class that has been loaded, parsed, and initialized , without a second step. Otherwise, take the third step.

The second step: Through the class's fully qualified name (can make class, database, Dynamic generation (proxy class) and so on) to get the binary byte stream, and according to this in the method area to open up the corresponding data structure of memory.

Step Three: create the object in the Java heap by opening up memory.

assuming that the Java heap is absolutely structured with memory, all the used memory is on one side, the free memory is on the other side, and a pointer in the middle is the indicator of the demarcation point, The allocated memory simply moves that pointer over the free space to a distance equal to the size of the object, which is called a "pointer collision" (Bump the Pointer); If the memory in the Java heap is not regular, the memory used and the free memory are interleaved, There is no way to simply perform a pointer collision, the virtual machine must maintain a list of which memory blocks are available, at the time of allocation from the list to find a large enough space to the object instance, and update the records on the list, this assignment is called "Free list". The choice of which allocation method is determined by whether the Java heap is structured or not, and whether the Java heap is structured or not, is determined by whether the garbage collector in use has a compression collation function. Thus, when using collectors with compact processes such as serial and parnew, the allocation algorithm used by the system is a pointer collision, while the use of CMS, a collector based on the mark-sweep algorithm, usually takes a free list.

Besides how to divide the free space, there is another problem to consider is that object creation is very frequent in the virtual machine, even if it is only modifying the location pointed to by a pointer, it is not thread-safe in the concurrency situation , it is possible to allocate memory for object A, the pointer has not yet been modified, and object B uses the original pointer for allocating memory. There are two ways to solve this problem, one is to synchronize the action of allocating the memory space--in fact, the virtual machine uses the CAs to match the failure retry to ensure the atomicity of the update operation, and the other is to divide the memory allocation action into different space according to the thread, That is, each thread pre-allocates a small chunk of memory in the Java heap, called the local thread allocation buffer (thread local Allocation buffer,tlab). Which thread allocates memory is allocated on the tlab of which thread, and only when Tlab runs out and assigns a new Tlab, does it require a synchronous lock. Whether the virtual machine uses Tlab, you can pass -xx:+/-usetlab parameters to set.

Fourth step: Put the memory reference into the stack

2.4. Memory layout of objects

The total is divided into three parts: the object header ( Header), instance data (Instance), and aligned padding (Padding).

Object header: Consists of two parts, the first of which is the run-time data that stores the object itself, such as a hash code ( Hashcode), GC generational age, lock status flag, thread-held lock, biased thread ID, bias timestamp, and so on, also known as Mark Word. The other part is the type pointer, which is the pointer to its class metadata, which the virtual machine uses to determine which class the object is an instance of. If the object is a Java array, then there must be a piece of data in the object header to record the length of the array

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. Since the automatic memory management system of the HotSpot VM requires that the object start address must be an integer multiple of 8 bytes

What is a reference to 2.5.java (object access positioning)

Java programs need to use reference data on the stack to manipulate the concrete objects on the heap, and the way objects are accessed depends on the implementation of the virtual machine, and there are two main ways of doing it:

Handle access: So In the Java heap, a piece of memory will be partitioned as a handle pool, where the handle address of the object is stored in the reference, and the handle contains the specific address information of the object instance data and the type data.

pointer access: then The layout of the Java heap object must consider how to place information about the access type data, and the object address is stored directly in reference, which is used by the hotspot

2.6.java OutOfMemoryError Exception

in the In the description of the Java Virtual Machine specification, in addition to the program counters, several other runtime areas of the virtual machine memory have the potential to occur outofmemoryerror (hereafter called oom) exceptions

First:java heap Overflow

The Java heap is used to store object instances, as long as the objects are constantly created, and the GC roots to the object to avoid the garbage collection mechanism from clearing these objects, a memory overflow exception occurs when the number of objects reaches the maximum heap capacity limit.

To test the detailed process:

configured in VM Auguments in the arguments of the run as->run configurations in eclipse:

-xms20m-xmx20m-xx:+heapdumponoutofmemoryerror

(-xms20m minimum memory 20m,-xmx20m maximum memory 20m,xx:+heapdumponoutofmemoryerror the virtual machine dump the current memory heap dump snapshot when a memory overflow exception occurs. Snapshot generated to the project )

See the Java heap overflow under the Project test Code COM.XUE.DEMO.JVMSTUDYDEMO.OUTOFMEMORYERROR exception package. java

2.7. virtual machine stack and local method stack Overflow

Stackoverflowerror

since the The hotspot virtual machine does not differentiate between the virtual machine stack and the local method stack, so for hotspot, although the-xoss parameter (set local method stack size) exists, it is actually invalid, and the stack capacity is only set by the-XSS parameter.

there is a limit to the memory assigned to each process by the operating system, such as 32-bit Windows limited to 2GB. The virtual machine provides parameters to control the maximum value of both the Java heap and the memory of the method area. The remaining memory is 2GB (operating system limit) minus XMX (maximum heap capacity), minus maxpermsize (maximum method area capacity), the program counter consumes little memory and can be ignored. If the memory consumed by the virtual machine process itself is not counted, the remaining memory is "partitioned" by the virtual machine stack and the local method stack. The larger the stack capacity each thread allocates, the less natural the number of threads can be established, and the easier it is to run out of memory when the thread is established.

2.8. Method area and run-time-constant pool overflow

Java.lang.OutOfMemoryError:PermGen Space

2.9 native Direct memory Overflow


2.java memory area and memory overflow exception

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.