002 Java memory area and memory overflow exception

Source: Internet
Author: User
Tags xms

1. Run-time data area
① program Counter Register is a small area of memory that can be thought of as the line number indicator of the byte code executed by the current thread if the thread is executing a Java method, Then this counter records the instruction address of the virtual machine bytecode that is executing if the native method is being executed, the value of this counter is empty (Undefined) This area is the only area in the Java virtual machine that does not stipulate any outofmemoryerror conditions
②java virtual machine stack thread private, life cycle is the same as thread describes the memory model that the Java method executes: Each method executes at the same time, creating a stack frame, which stores the local variable table, operands, Dynamic links and method exits and other information local variable tables hold the various basic data types, object references, and returnaddress types that are known at compile time (addresses to a bytecode directive) 64 long and double data of length will occupy 2 local variable space. The other one occupies 1. The memory space required for the local variable table is allocated at compile time, and the runtime does not change the size of the local variable table to specify two exception conditions for the virtual machine stack: 1. If the depth requested by the thread is greater than the depth allowed by the virtual machine, Stackoverflowerror;2 is thrown. If the stack is not able to request enough memory when dynamically expanding, it will throw OutOfMemoryError
The ③ local method stack acts like a virtual machine stack. The virtual machine stack is the Java method service that the virtual machine executes, and the local method stack is the native method service that is used by the virtual machine (the hotspot adds two stacks) and the exception that is thrown is the same as the virtual machine stack
The ④java heap Java heap is the largest piece of memory managed by a Java virtual machine, shared by all threads, created solely to hold object instances when the virtual machine is started, and where almost all object instances are allocated memory with the development of JIT and escape analysis technology, stack allocation, The reason for optimization techniques such as scalar substitution, where all object instances are allocated on the heap is not so absolute. The Java heap is the primary area of garbage collector management, and therefore can also be called the GC heap
The garbage collector mostly uses the generational algorithm, which can divide the Java heap into: The Cenozoic and the old age. More detail can be divided into Eden space, from Survivor space, to survivor space, such as memory allocation angle: Thread-shared Java heap can be divided into multiple threads private allocation buffer for better memory collection and memory allocation
The Java heap can be in a physically contiguous space, can be logically contiguous space can be fixed size, or can be extensible, the current mainstream virtual machines are implemented according to the extensible (through-XMX and-XMS control) when there is no memory in the heap to complete the allocation of instances, and cannot be extended, Throws a OutOfMemoryError exception
The ⑤ method area is the same as the heap, where all the threads share the memory area, store the class information loaded by the virtual machine, constants, static variables, the instant compiler compiled code, and so on the data hotspot uses the permanent generation implementation method area, can manage this part of memory with the management Java heap to use the permanent generation more likely to encounter memory overflow problem , permanent generation with-xx:maxpermsize limit, no problem in J9 and JRockit virtual machines as long as the process is not up to the available limit
In addition to the Java heap can not need continuous memory, you can choose a fixed size or extensible, you can also choose not to implement garbage collection when the method area does not meet the memory allocation, or throw OutOfMemoryError exception
⑥ Run constant Pool (runtime Constant) is part of the method area. Class file contains the version of the classes, fields, methods, interfaces, and other descriptive information, there is a constant pool, used to store the compilation period generated by a variety of literal and symbolic references, class loading into the method area constant pool storage in general, Virtual machine The direct reference to the translation is also stored in the run-time constant pool Another important feature of the regular pool relative to the regular pool in the class file is dynamic:Java does not require constants must only compile time to produce, not pre-placed in the class file in the constant pool of content to enter the run-time pool, the runtime, there may be new constants into the pool, this is more of the String Class intern () methodAs part of the memory area, it is subject to the memory limit of the method area and throws a OutOfMemoryError exception when the memory cannot be requested again
⑦ Direct Memory is not part of the data region when the Java virtual machine is running, nor is it a defined memory area of the VM specification, but this part is frequently used, which can also cause outofmemoryerror exceptions
2. Hotspot virtual Machine Object Exploration the process of object assignment, layout, and access in the Java heap ① object creation Java object is structured, that is, the allocated is placed in one piece, the unallocated memory is put in a piece, with a pointer as the boundary point, when the object needs to allocate memory, Moving the pointer to the space area requires the size of the memory, which is allocated as a "pointer collision (Bump the Pointer)" Java object is not structured, a list to record those blocks are available, those things are unavailable, allocation of the object needed to allocate memory to it, and then modify the allocation table, This allocation method is the "Free list" virtual machine allocation method is determined by the garbage collector with compression function, using serial, parnew and other compact process collector, using a pointer collision, using a CMS based on the mark-swap algorithm of the collector, Use the Idle list
Memory allocation synchronization: Use CAs and failed retries to ensure atomicity of the update operation, and one is to allocate a small chunk of memory per thread, called the local thread allocation buffer (thread local Allocation buffer,tlab), using Tlab using the virtual machine-xx:+/ -usetlab
After the memory allocation is complete, the virtual machine needs to initialize the allocated memory space to 0 values (excluding object headers). If you use Tlab, this process can be assigned to the Tlab allocation when the virtual confidential object to do the necessary settings, set the type of information (which class, the metadata information of the class), object hash code, object GC generational age, stored in the object header. Different virtual machine settings in different ways
The layout of the ② object's memory layout objects in memory can be divided into 3 areas: The object header, the instance data, and the object header that aligns the fill hotspot include two pieces of information: (1) used to store the object's own runtime data: hash code (HASHCODE), GC generational age, lock status flag, thread-held lock, Biased to thread ID, bias timestamp, etc., in 32 and 64 are virtual machines, respectively, 32bit and 64bit, called Mark Word,because this section stores information that is independent of the object's custom data, Mark Word is designed as a non-stationary data structure to store as much information as possible in a very small amount of space, which re-uses its own storage space based on the state of the object. (2) The other part of the object header is the type pointer (Klass Pointer), which points to its class metadata pointer, through which the pointer determines which class is an instance. Not all virtual machines must keep type pointers on objects, and the object's metadata information does not necessarily pass through the object itself. In the case of a Java array, there must also be a piece of data in the object header that records the length of the array, because the virtual machine can determine the size of the Java object from the metadata information of the ordinary Java object, but the size of the array cannot be determined from the array's metadata.
object to the actual storage of valid information, The order in which the various fields defined in the program (which inherit from the parent and subclass customizations require logging) is affected by the order of the virtual machine Assignment policy parameters (Fieldsallocatationstyle) and the field definition, and the default allocation policy for the hotspot is Longs/doubles, INTs, Shorts/chars, Bytes/booleans, oops (ordinary Object pointers), the same fields are always assigned together to meet the above allocations, and the variables defined in the parent class appear before the subclasses. If the Compactfields parameter value is True (the default is true), the narrower variables within that subclass may also be inserted into the void of the parent class variable.
The third part of alignment does not necessarily exist, just as a placeholder because the automatic memory management system of the Hotspot VM requires that the object start address must be an integer multiple of 8 bytes, in other words, the object must be an integer multiple of 8 bytes in size. The head portion of the object is exactly like a multiple of 8 bytes (1 time times or twice times), so when the object instance data part is not aligned, it needs to be filled by aligning the padding.

The access location of the ③ object depends on the implementation of the virtual machine (1) with the handle access, a chunk of memory is separated from the Java heap as a handle pool. The object handle is stored in reference, and the object handle contains the specific address of both the object instance data and the type data.
(2) With direct pointer access, the Java Heap object layout must consider how to access information about the type of data that is accessed, the object address stored in the Refere

Advantages of two object access methods
    • The biggest benefit of using a handle to access is that the stable handle address is stored in reference, and only the instance data pointers in the handle are changed when the object is moved (garbage collection is a very common behavior), and the reference itself does not need to be modified.
    • The greatest benefit of using a direct pointer is faster, which saves time overhead for pointer positioning
In the case of a virtual machine hotspot, it uses the second method of object access.

4 OutOfMemoryError Exception In addition to the program counter, the exception may occur in other runtime data regions of the Java Virtual Machine (oom).①java Heap OverflowThe control heap is not extensible: sets the minimum value of the heap the-XMS parameter is the same as the maximum value-xmx parameter-xx:+heapdumponoutofmemoryerror allows the virtual machine to dump the current memory heap dump snapshot for later analysis when a memory overflow exception occurs.

The ② virtual machine stack and the local method stack overflow in the hotspot virtual machine does not differentiate between the virtual machine stack and the local method stack, so for the 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.
Two types of exceptions are described in the Java Virtual Machine specification:
    • A Stackoverflowerror exception is thrown if the thread requests a stack depth that is greater than the maximum allowed depth for the virtual machine.
    • Throws a OutOfMemoryError exception if the virtual machine cannot request enough memory space on the scale stack.
In a single thread, either because the stack frame is too large or the virtual machine stack is too small, the virtual machine throws a Stackoverflowerror exception when the memory is not allocated. Using the-XSS parameter to reduce the stack content capacity and to define a large number of local variables increases the local variable table length by throwing stackoverflowerror exceptions. In the case of constantly creating threads, the larger the stack capacity each thread allocates, the less the number of threads that can be established, the easier it is to run out of memory when the thread is established. The memory overflow caused by multithreading has been established, and in the case of not reducing the number of threads or replacing a 64-bit virtual machine, it can only be exchanged for more threads by reducing the maximum heap and reducing the stack capacity.
In a Windows platform virtual machine, Java threads are mapped to the operating system's kernel thread.

③ method zones and run times in JDK 1.6 and earlier, because constant pool allocations are within a permanent generation, we can limit the size of the method area by-xx:permsize and-xx:maxpermsize, thereby indirectly limiting the capacity of the constant pool.

String.intern () returns the referenced test
  
 
  1. public class RuntimeConstantPoolOOM {
  2. public static void main(String[] args) {
  3. public static void ( string [] args {
  4. string = new stringbuilder ( "computer" append ( "Software" tostring ();
  5. System.out.println(str1.intern() == str1);
  6. string = new stringbuilder ( "ja" append ( "va" tostring ();
  7. System.out.println(str2.intern() == str2);
  8. } }
  9. }
JDK1.6 of two false;JDK1.7 ture and FalseIn JDK 1.6, the Intern () method copies the first encountered string instance to the permanent generation, returning a reference to the string instance in the permanent generation, and the string instance created by StringBuilder on the Java heap, so it is not necessarily the same reference and will return false. The Intern () implementation of JDK 1.7 (and some other virtual machines, such as JRockit) no longer replicates the instance, but only the first occurrence of the instance reference in the constant pool, so the reference returned by intern () and the string instance created by StringBuilder are the same.
The str2 comparison returns false because the string "Java" has already occurred before execution of Stringbuilder.tostring (), the string constant pool already has its reference, and does not conform to the "first occurrence" Principle (JDK1.6 and 1.7 are all), returns the reference in the constant pool, and the "computer Software" string is the first occurrence, and therefore returns true.
The method area is used to store information about class, such as its name, access modifier, Chang, field description, method description, and so on.

④ Direct native Memory overflow directmemory capacity can be specified by-xx:maxdirectmemorysize, and if not specified, the default is the same as the Java heap maximum (-xmx specified).
Memory overflow caused by directmemory, an obvious feature is that the heap dump file will not see the obvious exception, if the reader found that the dump file is very small, and the program directly or indirectly using NIO, then you can consider whether this is the reason.

From for notes (Wiz)

002 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.