Java GC algorithm

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/heyutao007/article/details/38151581

1. JVM Memory Composition Structure


The JVM memory structure consists of heap, stack, local method stack, method area and so on, and the structure diagram is as follows:



1) Heap


All the memory of objects created by new is allocated in the heap, and its size can be controlled by-XMX and-XMS. The heap is divided into the Cenozoic and the old generation, and the Cenozoic is further divided into the Eden and survivor areas, the survivor is composed of Fromspace and tospace, the structure diagram is as follows:




Cenozoic. New objects are used to allocate memory in the Cenozoic, when Eden space is insufficient, the surviving objects will be transferred to the survivor, the Cenozoic size can be controlled by-xmn, you can also use-xx:survivorratio to control the proportions of Eden and survivor.


The old generation is used to store objects that are still alive in the Cenozoic after multiple garbage collection (also known as minor GC)


2) stack


Each thread executes each method by applying a stack frame in the stack, each of which includes a local variable area and an operand stack to hold temporary variables, parameters, and intermediate results during the method call.


3) Local Method stack


Used to support the execution of the native method, which stores the state of each native method call


4) Method Area


Contains the class information to load, static variables, constants of the final type, properties, and method information. The JVM uses persistent generations (or permanent generations, permanetgeneration) to store the method area, which can be specified by-xx:permsize and-xx:maxpermsize to specify the minimum and maximum values.

In the past (when the custom ClassLoader is not very common), the classes are mostly "static", are rarely unloaded or collected, and are therefore referred to as "permanent (Permanent)". Also, because class classes are part of the JVM implementation and are not created by the application, they are considered "non-heap (non-heap)" Memory.


In the hotspot JVM prior to JDK8, storing these "permanent" areas is called "permanent generation (permanent generation)". The permanent generation is a contiguous heap space, which is set to the maximum assignable memory space by setting the parameter-xx:maxpermsize at the command line before the JVM starts, the default size is 64M (64-bit JVM is 85M by default due to pointer bloat). The permanent garbage collection is bundled with the old generation, so whoever is full will trigger the garbage collection of the permanent generation and the old age. However, one obvious problem is that when the JVM loads more class information than the parameter-xx:maxpermsize set, the application will report oom errors.

The permanent generation is completely removed from the JDK8. So the parameters of the permanent generation-xx:permsize and-xx:maxpermsize are also removed.

In JDK8, Classe metadata (the virtual machines internal presentation of Java Class) is stored in metaspace memory called native. Some of the new flags were added:
The initial space quota for the-xx:metaspacesize,class metadata, in bytes, which triggers garbage collection for type unloading, and the GC adjusts the value: if a large amount of space is freed, the value is appropriately lowered If a small amount of space is released, it is appropriate to increase the value if it is not more than maxmetaspacesize (if set).
-xx:maxmetaspacesize, the maximum space that can be allocated for class metadata. The default is no limit.
-xx:minmetaspacefreeratio, as a percentage of the minimum metaspace remaining space after GC, reduces garbage collection due to class metadata allocated space
-xx:maxmetaspacefreeratio, after GC, the largest percentage of metaspace remaining space is reduced to garbage collection caused by class metadata free space

By default, the assignment of class metadata is limited only by the total amount of native memory available. You can use Maxmetaspacesize to limit the maximum memory that can be allocated for class metadata. The Dead class loader and class are garbage collected when the memory used by class metadata reaches metaspacesize (32-bit CLIENTVM default 12mbytes,32 bit SERVERVM default is 16Mbytes). Setting Metaspacesize to a higher value can delay the occurrence of garbage collection.

After introducing the JVM memory composition structure, let's look at the JVM garbage collection mechanism.



2. Java GC Basic algorithm

2.1. Reference count (reference counting)
Principle: This object has a reference, then +1; Deletes a reference, then-1. Only objects with a collection count of 0 are used.
Cons: (1) Unable to handle circular reference issues. For example, objects A and B have field B, a, a.b=b and b.a=a, except that these 2 objects are no longer referenced, and in fact the 2 objects are no longer accessible, but the reference counting algorithm cannot reclaim them. (2) The method of reference counting requires a compiler's mate. The compiler needs to generate additional code for this object. If the assignment function assigns this object to a reference, you need to increase the reference count for this object. Also, when the life cycle of a reference variable ends, the reference counter for this object needs to be updated.

The method of reference counting is not actually used by the JVM because of its significant disadvantage.


2.2. Copy (copying)
Principle: Divide the memory space into 2 equal regions, using only one region at a time. During garbage collection, traverse the current area of use and copy the objects being used to another area.
Pros: There are no fragmentation issues.
Disadvantages:
(1) Pause the entire application.
(2) requires twice times of memory space.


2.3. Mark-Sweep (Mark-and-sweep)
Principle: For a "Live" object, it must be traced back to its existence in the stack, static storage of the reference. The reference chain may pass through several object hierarchies, and the algorithm is based on the graph and takes a depth-first search.
Phase one: Start by traversing all references from GC roots, marking a live object.
Second stage: The heap is traversed, and the unmarked objects are purged.
Pros: Resolves the issue of circular references.
Disadvantages:
(1) suspend the entire application;
(2) Memory fragmentation is generated.
(3) Whether or not your object is accessible, that is, whether it is rubbish or not, it is time-consuming to be inspected at a clear stage.

This technique is used in the early sun version.


2.4. Marking-Compression (mark-compact)
First stage: With Mark-sweep, Mark living object,
Phase two: This stage organizes all tagged activity objects to the bottom of the heap
Advantages:
(1) Avoid the problem of marking the scanned fragments;
(2) Avoid space problems that stop copying.


2.5, sub-generational (generational collecting)
Principle: The garbage collection algorithm based on the object life cycle analysis. The objects are divided into young generation, old generation, and enduring generations, and the different life cycles are recycled using different algorithms (one of the 2-3 methods, 4 adaptive).

j2se1.2 Use this algorithm later

The JVM uses different garbage collection mechanisms for the Cenozoic and the old generation respectively


2.5.1, the New generation GC (Minor GC):


Refers to the garbage collection action occurring in the new generation, because most Java objects have the characteristics of the Minor, so the GC is very frequent, the general recovery speed is relatively fast.


The new generation usually has a shorter survival time, so the so-called copying algorithm is used to retrieve the surviving object based on the copying algorithm, and copy it into a completely unused space, corresponding to the Cenozoic, which is copy between Eden and Fromspace or Tospace. The Cenozoic uses a free pointer to control the GC trigger, the pointer keeps the last allocated object in the Cenozoic interval, and when a new object is allocated memory, it is used to check if the space is sufficient and not enough to trigger the GC. When objects are continuously allocated, the objects gradually go from Eden to Survivor, and finally to the old generation,




2.5.2, Old generation GC (Major gc/full GC):


Refers to the GC that occurred in the old age. The old generation and the new generation, the object survival time is longer, more stable, so the mark (Mark) algorithm for recycling, so-called Mark is to scan out the surviving objects, and then to reclaim unmarked objects, after recycling the empty space is either merged, or marked out for the next allocation, The bottom line is to reduce the loss of efficiency caused by memory fragmentation.


The speed of the MAJORGC is generally 10 times times slower than the Minor GC.


Thinking in Java takes a wordy salutation to the Java GC: "Adaptive, generational, stop-copy, tag-scan" garbage collector.


Conditions that lead to GC:
1, tenured is written full
2, Perm is written full
3, explicit invocation of System.GC ().
4. The domain allocation policy changes dynamically for the heap after the last GC.

Java GC algorithm

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.