"In-depth understanding of Java virtual machines" Java memory area model, object creation process, common oom

Source: Internet
Author: User

This article is from the "in-depth understanding of Java Virtual Machine," a book, it is very recommended that you look at this book. Recently began to read this book, intends to open a series of related, to summarize the book's important points of knowledge. Uh, uh, well, that picture request framework is not urgent, because this request framework design content is relatively broad, the current spare time is being prepared, and then will be put up. Before we finish, let's learn some other knowledge.
1. Memory modelThe Java virtual machine, in the course of executing a Java program, divides the memory that it says to manage into several different data regions, as shown in the following: Images from a network
(1) Procedure counter (program Counter Register)Thread Private。 The program counter is a small memory space that can be viewed asThe line number indicator of the byte code executed by the current thread。 The bytecode interpreter works by changing the value of this counter to select the next byte-code instruction that needs to be executed, branching, looping, jumping, exception handling, and thread recovery registry functions all need to rely on the value of this counter to complete.in order for the thread to switch back to the correct execution location, each thread needs to have a separate program counter, and the counters between the threads do not affect each other ., isolated storage. This type of memory area is called"Thread-private" memory。program counter, is the only area in the Java Virtual Machine specification that does not stipulate any outofmemoryerror。
(2) Java Virtual machine stackAlsothread-Private, with the same life cycle as the thread。 The virtual machine stack describes the memory model that the Java method executes:Each method will create a stack frame at the same time as the execution, for storinglocal Variable Table、operand Stacks、Dynamic Links、Method Exportand other information. We usually divide Java into heap memory and stack memory, where the"Stack" is the current virtual machine stack, or the local variable table part of the virtual machine stack .。 The memory space required for the local variable table iscompleting allocations during compilation, when you enter a method, This method needs to allocate how much local variable space is allocated in the stack frame, which is completely deterministic and does not change the size of the local variable table while the method is running .。 For Java Virtual machine stacks, there are two exceptions: 1) If a thread requests a stack depth greater than the virtual machine allows, it throwsStackoverflowerror2) If the virtual machine stack is dynamically expanding and cannot request enough memory, it will throwOutOfMemoryError;         The Java Virtual machine's interpretation execution engine is called the "stack-based execution engine", where the "stack" is the operand stack. So we also call Java virtual machines stack-based, unlike Android virtual machines, which are register-based.
(3) Local approach stack (Native method Stack)Thread Private。 The local method stack and the virtual machine stack play a very similar role, and the difference between them is mainlyThe virtual machine stack is a Java method (i.e. bytecode) service for virtual machines, while the local method stack is the native method service used by the virtual machine。 Similar to the virtual machine stack, the local method stack throwsStackoverflowerrorAndOutOfMemoryErrorAbnormal.
Java Heap (4)All Threads Share。 Java Heap increated at virtual machine startupis the largest piece of memory managed by a Java virtual machine.the only purpose of the Java heap is to hold object instances and arrays 。 The Java heap is the primary area of garbage collector management and therefore is also a "GC heap." From Memory RecyclingPoint of view, since most collectors now use generational collection algorithms, the Java heap can be subdivided into: CenozoicAnd old age, then subdivide one point: Eden Space、From survivor Space、To Survivor Spacesuch as From Memory allocationView, a thread-shared Java heap can divide multiple thread-Private allocation buffers(Thread Local Allocation buffer,tlab).    However, regardless of the partition, which area is stored is an object instance. The Java heap does not physically require contiguous memory, as long as it is logically contiguous. If there is no memory in the heap to complete the instance assignment and can no longer be expanded, it will throwOutOfMemoryErrorAbnormal.
(5) method areaAll Threads Share。 For storing class information, constants , static variables , and immediate compiler-compiled code that have been loaded by the virtual machine and other data. The method area also has an alias called Non-heap (Not a heap), which is used to differentiate it from the Java heap. For a hotspot virtual machine, the method area is also used to be called the "permanent Generation" (permancent Generation), but this is only for the hotspot virtual machine, the other virtual machine implementation does not have this concept. The garbage collection behavior is relatively rare in this area, but it is not a collection,The memory recovery target for this area is primarily for the recovery of constant pools and for the unloading of types。To run a constant-rate pool:The run-time-constant pool belongs to the method area. class file, in addition to the version, field, method, interface, and other descriptive information, there is also a constant pool of information for holds various literal constants and symbolic references generated during the compilation period, this part of the contentwill be stored in the run-time constant pool of the class load backward into the method area。 In other words, this part of the content, at compile time just put into the constant pool information, to the load, will be placed in run a constant-rate poolto the.running a constant pool county attributed to the class file, another important feature of the Const pool is the dynamic, the Java language does not require constants to be generated only at compile time, which isThe contents of a constant pool in a class file are not pre-placed to enter the run-time pool of the method area , and new constants may be placed in the pool during the run , this feature is used by developers more than the Intern () method of the String class.
When the method area fails to meet the memory allocation requirements, the OutOfMemoryError exception is thrown, and the constant pool belongs to the method area, which can also throwOutOfMemoryErrorAbnormal.

(6) Direct MemoryDirect Memory is not part of the data area when the virtual runtime is running, nor is it an area of memory defined in the Java Virtual Machine specification. However, this part of memory is also used frequently and may causeOutOfMemoryErrorAbnormal. The allocation of direct memory is not limited by the size of the Java heap, but it requires the size of the native total memory and the limit of the processor addressing space. A typical example of using direct memory is the NIO added to JDK1.4. The specific contents of NiO can be seen in theThe seventh wave of the Java written examination question arrangementthe sixth part of the ".
Memory Area Model Summary:(1) Thread-Private Zone: Program counter, virtual machine stack, local method stack, (2) All threads shared area: Java heap, method area; (Note: Direct memory is not part of the virtual Machine memory model) (3) No exception area: Program Counter; (4) Stackoverflowerror Exceptions: Java Virtual machine stack, local method stack, (5) OutOfMemoryError exception: Four regions except program counter, Java Virtual machine stack, local method Stack, Java heap, method area, direct memory also appears outofmemoryerror.
2. Object creation, object memory layout, object access and positioning2.1 Creating a process for objectsAt the language level, Java creates objects through a keyword new. In a virtual machine, when a new command is encountered, the following creation process begins: (1) Determine if the class is loaded, parsed, initializedVirtual opportunity to a new directive, first check whether the specified parameter can be positioned in a constant pool to a class symbol reference, and check whether the symbol reference represents the class has been loaded, parsed and initialized. If not, perform the appropriate class loading process first. (2) allocating memory for new objectsAs mentioned earlier, the memory allocation of objects is in the Java heap. The task of allocating space to an object is equivalent to dividing a certain size of memory from the Java heap, in which case there are two possibilities in the Java heap, one of which is that the memory in the Java heap is absolutely regular, and that the memory in the Java heap is not regular. So there are two ways to allocate: 1) Java heap Memory is structured, that is, all used memory is put aside, free memory on the other side, in the middle of a pointer as a demarcation point indicator, at this time,allocating memory only needs to move this pointer over the free space to a distance equal to the size of the object, this approach is also known as "Pointer Collision(Bump the Pointer); 2) Java heap memory is not structured, that is, the memory used and the free memory interleaved with each other, there is no way to simply move the pointer, at this time the allocation scheme is,The virtual machine must maintain a list of which memory blocks are available and, when allocated, find a large enough control to be partitioned into the object instance and update the records on the list, this approach is also known as "Free list"(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. Therefore, for the serial, parnew and other compact processes with the garbage collector, the system uses a pointer collision algorithm, for the CMS based on the mark-sweep algorithm of collectors, usually use the idle list algorithm.
(3) Resolving concurrency security issuesAfter determining how to divide the memory space, there is also a problem is that the creation of objects in the virtual machine is very frequent behavior, for example, it is possible to allocate memory for object A, the pointer has not been modified, object B and use the original pointer to allocate memory, to solve this concurrency problem, there are generally two scenarios: 1) synchronous processing of the action of allocating memory space, for example, the virtual machine using CAS with the failure retry to ensure the atomicity of the update operation; 2) The other way is to divide the memory allocation action into different space by thread, that is, each thread 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, on which thread the Tlab is allocated. Only when the Tlab runs out and assigns a new Tlab, does it require a synchronous lock and the virtual machine uses Tlab, which can be set by the-xx:+/-usertlab parameter.
(4) Initialize the allocated memory spaceAfter the memory allocation is complete, the virtual machine allocates the memory space to the 0 value (excluding the object header), which can also be done in advance to Tlab allocation if Tlab is used. It is this step,To ensure that the instance field of our object can be used directly in Java code without assigning an initial value。 Attention The instance field of the object is all zero, and is not initialized according to the initial value in the program
(5) Set object header for object instanceAfter the completion of the work, the virtual machine to the object to make the necessary settings, mainly to set the object header information, such as the object is which class instance, how to find the metadata information of the class, the object's hash code, the object's GC generational age, etc... (6) Initialize objects <init> methodsIn fact, after the completion of the work, from the virtual machine point of view, a new object has been generated, but from the perspective of the Java program, object creation has just begun, the object instance of the field is only zero value, but also through the <init> method to initialize, Initialize the object according to the programmer's wishes. At this point, a truly usable object is fully generated.
2.2 Memory layout of objectsAfter the previous creation, an object has been successfully generated, and memory has been allocated in the Java heap. What exactly is this object in the Java heap memory? And what are the parts?    This involves the memory layout of the object. In different virtual machine implementations, objects have different memory layouts, with the most commonly used hotspot virtual machine as an example, the layout of objects stored in memory is divided into 3 areas:Object Headers (header)、instance (Instance data)、align Fill (Padding)。 1) Object header:Contains two pieces of information, part of which is used to Store run-time data for the object itself, such as hash code, GC generational age, lock status flag, and so on; the other part is 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, the object header also has a piece of data to record the length of the array, because the virtual machine can determine the size of the Java object through the metadata information of the ordinary Java object, but the array size cannot be determined from the array's metadata. 2) instance data:the part that really stores the valid information for the object. That is, the various types of field content defined in the program, including those inherited from the parent class, as well as those defined in the subclass, are recorded in the instance data. 3) align fill: Not necessarily exist, only play the role of placeholder, for the hotspot, the virtual machine's automatic memory management system requires that the object address must be an integer multiple of 8 bytes, so if the object instance data part is not aligned, You need to fill it up by aligning the padding.
2.3 Object access and positioningobject is set up to use the object, our use of data is through the stack of reference data to manipulate the concrete objects on the heap, for different virtual machine implementations, reference data types have different definitions, mainly the following two ways to access: 1) using the handle to access。 At this point, a chunk of memory will be drawn out of the Java heap asHandle Pool, the handle address of the object is stored in the reference, and the handle contains theobject instance DataAndtype Dataof individualSpecific address informationSuch as:
2) Use direct pointer access。 At this point, the address of the object is stored in reference. Such as:

As mentioned above, the so-called object type, in fact, refers to which class the object belongs to. There are advantages to the above two types of object access, the greatest benefit of using handle access is that the reference is stored in a stable handle address, when the object is moved (garbage collection when moving the object is very common behavior), only changes in the handle of the instance data pointer, and reference itself does not need to modify The biggest benefit of using direct pointer access is faster, which saves time spent on pointer positioning (based on the pointer positioning of object instance data), and because object access is very frequent in Java, this overhead is a significant execution cost. For a hotspot, the second option is chosen.
3. Common Oom and SOFOom is divided into two situations:memory Overflow (Overflow)Andmemory Leak (Leak)。OOM:OutOfMemoryError Exception,ThatMemory OverflowWhen the program is requesting memory,There is not enough room for its use, there was an out of Memory, i.e.requires that the allocated memory exceeds the system can give you, the system can not meet the requirements, and then overflow. memory overflow is divided into overflow and underflow ,such as the stack, the stack when the stack is bound to create a space overflow, called overflow, stack empty and then do the fallback stack also produces a space overflow, called underflow. SometimesMemory leaks can cause memory overflowCalledMemory Leaks(memory leak), meansThe program cannot release the requested memory space after it has requested memory, a memory leak hazard can be ignored, but memory leaks accumulate consequences are serious, no matter how much memory, sooner or later will be the light, for example, that is, the system's basket (memory) is limited, and you apply for a basket, have not been returned (forgotten or lost), resulting in a memory leak. When you need to use the basket, and then apply, so repeated, the final system of the basket can not meet your needs, and ultimately byMemory leak causes memory overflow。
Oom encountered: (1)Java Heap OverflowJThe Ava Heap is used to store object instances, as long as we constantly create objects without reclaiming them in time (i.e.Memory Leaks), a memory overflow exception is generated when the number of objects reaches the maximum heap capacity limit. (2)Method Area Overflow   The method area is used to store information about class, such as its name, access modifier, Chang, field description, method description, and so on.

Exception information: Java.lang.OutOfMemoryError:PermGen space

Method area Overflow is also a common memory overflow exception, and a class is very demanding if it is to be reclaimed by a garbage collector. This is especially important in applications that generate a large number of classes on a dynamic basis.


SOF:stackoverflow ( stack Overflow )     This error is thrown when the application is recursive too deep and a stack overflow occurs. because the stack generally defaults to 1-2m, in the event of a dead loop or a large number of recursive calls, in the continuous compression stack process, resulting in a stack capacity of more than 1m, resulting in overflow. Stack Overflow Reason: (1) recursive invocation (2) a large number of loops or dead loops (3) Global variables are too large (4) array, List, map data too big
(Note: The image from the article is from the network)

"In-depth understanding of Java virtual machines" Java memory area model, object creation process, common oom

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.