Java Memory Management

Source: Internet
Author: User
Tags compact java throws

Java programs actually give the power of memory control to a Java virtual machine, and in the event of a memory leak and overflow problem, if you don't know how the virtual machine is using memory, then troubleshooting will be an incredibly difficult task. and understand the memory management of Java, help optimize the JVM, so that your application to achieve the best performance experience. So wait for what, quickly follow me to learn this knowledge bar ~
Java memory management is divided into two areas: memory allocation and garbage collection, let's look at one of the following.

The JVM defines 5 zones for storing runtime data, as follows:


First, the procedure counter (PC, program Counter Register)
Program Counter Register is a small amount of memory space, which can be seen as the current thread execution of the bytecode of the line number indicator, the bytecode interpreter works by changing the value of this counter to remove a need to execute the bytecode instruction, branch, jump, loop, This counter is required for basic functions such as exception handling, thread recovery, and so on.
When the thread is executing a Java method, this counter records the address of the bytecode instruction of the virtual machine being executed, and when the native method is executed, the counter value is empty.
Note: Each thread will have a separate program counter, and the only one that does not appear is oom.
Second, Java stack/virtual machine stack (VM stack)
The Java stack is the memory model implemented by the methods in Java, each of which creates a stack frame, which is used to store local variable tables, operand stacks, dynamic links, method exits, and so on, each method from the call until the completion of the process, Corresponds to a stack frame in the virtual machine stack into the stack to the process.
The local variable table holds the various basic data types known to the compiler (Boolean, Byte, char, short, int, float, long, double), object reference, and ReturnAddress type (which points to the address of a bytecode directive).
Exception probability: There are two exceptions to the stack, and if the thread requests a stack depth greater than the stack's allowable depth, the Stackoverflowerror exception will be thrown, and if the virtual machine stack can be dynamically extended, it cannot be applied to enough memory for expansion. OutOfMemoryError exception will be thrown
Third, local methods stack (Native method Stack)
The role of the local method stack with the Java stack is very similar, and the difference between them is simply the Java stack execution Java method, the local method stack executes the local method. Some virtual machines combine the local method stack and the virtual machine stack directly.
Exception probability: As with the Java stack, stackoverflowerror and Outofmemeryerror exceptions can be thrown
Iv. Java Heap
For most applications, the Java heap is the largest piece of memory managed by a Java virtual machine and is created when the virtual machine is started. The only purpose of this memory area is to hold object instances, where almost all object instances are allocated memory, and of course the Java heap is the main area of garbage collector management when we talk about garbage collector content later.
From the memory allocation point of view, the thread-shared Java heap may divide multiple thread-private allocation buffers (Tlab). The Java heap can be in a physically discontinuous memory space as long as it is logically contiguous. In implementation, both fixed-size and extensible can be implemented.
Exception probability: A Outofmemeryerror exception is thrown if there is no memory in the heap to complete the instance assignment and the heap cannot be extended again
V. Method area
The method area is used to store data such as the class information that has been loaded by the virtual machine, constants, static constants, immediate compiler-compiled code, and so on.
1) Run the constant-rate pool
The run-time pool is part of the method area, and in addition to the description of the class's version, field, method, interface, and so on, there is a constant pool that holds the various literal and symbolic references generated by the compiler, which will be stored in the runtime exception constant pool after the ClassLoader enters the method area.
The constant pool holds the constants in the run, and we know that the Intern method of the string type is to put the value of the strings into the constant pool.
The garbage collection behavior is relatively rare in this area, but it is not the data into the method area permanent existence, the area of the memory recovery target is mainly for the recovery of the constant pool and the type of unloading.
Exception probability: A Outofmemeryerror exception is thrown when the method area does not meet the memory allocation requirements
Direct Memory
Direct memory is not part of the data area of the virtual runtime, and a channel-to-buffer Io method is introduced in the NIO class, which can allocate out-of-heap memory directly using the native function library. It is then manipulated by a Directbytebuffer object stored in the Java heap as a reference to this memory, or directly using unsafe.allocatememory, but this is not recommended.
The allocation of direct memory is not limited by the size of the Java heap, but is limited by the size of the native memory, and all may throw outofmemoryerror exceptions.
Description
Thread Private: Program counter, Java stack, local method stack
Thread sharing: Java heap, method area

Garbage collection (garbage collection, referred to as GC) can automatically empty objects that are no longer used in the heap, and programmers can reduce the chance of making mistakes in programming because they do not need to manually free up memory. With garbage collection, programmers can avoid some pointers and memory leak related bugs (this kind of bug is usually very covert), but on the other hand, garbage collection takes more computing time, garbage collection is actually the responsibility of the original programmer transferred to the computer.

In Java, the object is used by reference, and if no longer has a reference to the object, then we can no longer invoke or manipulate the object. Such objects will not be reachable (unreachable). Garbage collection is used to free up memory occupied by unreachable objects. This is the basic principle of garbage collection.

There are 4 types of references in Java, from strong to weak, in the following sequence:
1) Strong references (strongreference) are the most common references, similar to the following: "Object obj = new Object ()". If an object has a strong reference, the garbage collector will never recycle it. When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues.
2) Soft Reference (Soft Reference)is used to describe some useful, but not necessary, objects., if there is enough memory space, the garbage collector does not recycle it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.
3) A weak reference (WeakReference) is also used to describe a non-required object, but its strength is weaker than the soft reference, the object associated with the weak reference only survives until the next garbage collection occurs, and when the garbage collector is working, the object associated with the weak reference is reclaimed, regardless of whether the current memory is sufficient. However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.
4) virtual Reference (Phantomreference), also known as Phantom Reference or Phantom Reference, is the weakest reference relationship, whether an object has a virtual reference, does not affect its lifetime at all, and cannot obtain an object instance from a virtual reference.

When GC is being recycled, it is necessary to check whether the soft reference object is reclaimed by the algorithm, and the GC is always recycled for weak reference objects. Weak reference objects are more easily and faster to be recycled by GC. Although GC must recycle weak objects at runtime, the weak object group of complex relationships often takes several GC runs to complete. Weak reference objects are often used in the map structure to refer to objects with a large amount of data, and once the strong reference to the object is NULL, the GC can quickly reclaim the object space.

The main feature of Soft reference is its strong reference function. This kind of memory is only recycled when there is not enough memory, so when memory is sufficient, they are usually not recycled. In addition, these reference objects are guaranteed to be set to NULL before Java throws a OutOfMemory exception. It can be used to implement the cache of some commonly used images, realize the function of the cache, and ensure the maximum use of memory without causing outofmemory.
Here is an example of using a weak reference:
    Request an Image object  image=new image ();       Create Image Object   //Use image  ...  //run out of image, set it to soft reference type, and release strong reference;  softreference sr=new softreference (im Age);  Image=null;  ..... Next use  if (sr!=null)   image=sr.get ();  else{  image=new image ();  Because the GC has been released because of low memory, the image needs to be reloaded;  sr=new softreference (image);  }  

One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled.

The following example associates a virtual reference to a reference queue:

Referencequeue refqueue = new Referencequeue (); Reference'll be stored in the this queue for cleanupdigitalcounter digit = new Digitalcounter (); phantomreference<digitalcounter> Phantom = new phantomreference<digitalcounter> (digit, refQueue);


GC algorithm

The "Mark-clear" (mark-sweep) algorithm, divided into "mark" and "clear" two stages: first mark out all the objects that need to be recycled, after the mark is complete, all the tagged objects are collected uniformly.


Its main drawbacks are:
1, efficiency problems, marking and removal process is not high efficiency;
2, the space problem, the mark after the purge will produce a large number of discontinuous memory fragments, too much space debris can cause, when the program will need to allocate a large object in the future operation can not find enough contiguous memory and have to trigger another garbage collection action in advance;

The Copying algorithm, which divides available memory by capacity into two blocks of equal size, using only one piece at a time. When this piece of memory is exhausted, copy the surviving object to the other piece, and then clean up the used memory space once. This makes each one of the pieces of memory recycling, memory allocation will not consider the complexity of memory fragmentation, as long as the mobile heap top pointer, in order to allocate memory, simple implementation, efficient operation.


Its main drawbacks are:
1, just this algorithm is to reduce the memory of the original half, a little too wasteful;
2, the object survival rate is higher, it is necessary to perform more replication operations, the efficiency will be lower;

The mark-compact algorithm, the tagging process is still the same as the "mark-purge" algorithm, but the next step is not to clean up the recyclable objects directly, but to let all surviving objects move toward one end, and then directly clean out the memory outside the end boundary. In this way, there are more contiguous memory spaces.


The above algorithms are mixed by generational recycling (generational collection), generally dividing the Java heap into young Generation (Cenozoic), old Generation (older), and permanent Generation (persistent generation), so that the most appropriate recovery algorithm can be used according to the characteristics of each age.


1) in young generation, there is a space in the Eden space, mainly for the newborn objects, and two survivor Spaces (from, to), they are always the same size, they are used to store each garbage collection survived after the object.
3) in young generation block, garbage collection is generally used copying algorithm, fast. At each GC, the surviving objects are first copied from Eden to a survivorspace, and when the survivor space is full, the remaining live objects are copied directly to Oldgeneration. Therefore, after each GC, the Eden memory block is emptied.
4) in the old generation block in the main storage applications in the long life cycle of memory objects, garbage collection is generally used mark-compact algorithm, slower, but reduce memory requirements.
5) in permanent generation, it is used primarily to put the JVM's own reflective objects, such as class objects and method objects.
6) Garbage collection sub-level, 0 level for all (full) garbage collection, the old section of garbage collection, 1 or more of the garbage collection, will only recover the garbage in young, memory overflow usually occurs after the old or perm segment garbage collection, There is still no memory space to accommodate new Java objects.

Description
From, to: these two regions are equal in size, equivalent to two regions in the copying algorithm, and minor collection when new objects cannot be placed in the Eden area. The JVM uses the copying algorithm to copy the Eden Zone and the reachable objects from the from zone to the to area. After a garbage collection, the Eden Zone and the from zone are emptied, and the to area is tightly stocked with surviving objects. The from zone then becomes the new to zone, and the to zone becomes the new from zone. If the minor collection is found to be out of the area, then part of the object is put into the mature generation. On the other hand, even if the to area is not full, the JVM will still move long enough to mature generations. If the mature generation fills the object and cannot move into the new object, the major collection (full recycle) is triggered.

Java Memory Management

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.