Java GC algorithm Garbage Collector

Source: Internet
Author: User

Java GC algorithm Garbage Collector
Overview of GC algorithm Garbage Collector

Garbage Collection is often called "GC". It was born in The Lisp Language of MIT in 1960. After more than half a century, it has become very mature.

In jvm, program counters, virtual machine stacks, and local method stacks are all destroyed along with threads. Stack frames perform inbound and outbound operations as methods enter and exit, automatic Memory cleaning is implemented. Therefore, the garbage collection of memory is mainly concentrated in the java heap and method area. During the program running, the allocation and usage of this part of memory are dynamic.

 

Object survival judgment

There are two methods to determine whether an object is alive:

Reference count: each object has a reference count attribute. Add a reference count plus 1, and the reference release count minus 1. When the count is 0, the reference count can be recycled. This method is simple and cannot solve the problem of repeated object reference.

Reachability Analysis: searches down from GC Roots, and the paths that are searched are referred to as reference chains. When an object is connected to GC Roots without any reference chain, it is proved that this object is unavailable. Inaccessible object.

In Java, GC Roots includes:

Objects referenced in the Virtual Machine stack.

Object referenced by a Class static property object in the method area.

Objects referenced by constants in the method area.

The object referenced by JNI in the local method stack.

 

Garbage collection algorithm mark-clearing Algorithm

The Mark-Sweep (Mark-Sweep) algorithm, like its name, is divided into two stages: "Mark" and "clear": First Mark all objects to be recycled, after the tag is complete, all marked objects are recycled. It is said that it is the most basic collection algorithm, because the subsequent collection algorithm is based on this idea and its shortcomings are improved.

It has two main disadvantages: efficiency, low efficiency in the process of marking and clearing, and space. After marking is cleared, a large number of discontinuous memory fragments are generated, too many space fragments may cause the program to fail to find enough continuous memory when a large object needs to be allocated during future running, and it has to trigger another garbage collection action in advance.

 

 

 

Copy Algorithm

The Copying collection algorithm divides the available memory into two equal-size blocks by capacity, each using only one of them. When the memory of this block is used up, copy the still living objects to the other block, and then clear the used memory space.

In this way, the memory is recycled every time, so you don't need to consider the memory fragmentation and other complex situations when allocating the memory. As long as you move the heap top pointer and allocate the memory in sequence, the implementation is simple, efficient operation. The cost of this algorithm is to reduce the memory to half of the original size, and the efficiency is reduced when objects in the long-lived period are continuously copied.

 

 

 

Mark-Compression Algorithm

The replication collection algorithm performs many replication operations when the object survival rate is high, which reduces the efficiency. More importantly, if you do not want to waste 50% of the space, you need to allocate extra space for guarantee to deal with the extreme situation where 100% of all objects in the memory to be used survive, therefore, this algorithm cannot be directly used in the old age.

According to the characteristics of the old age, someone proposed another Mark-Compact algorithm, which is still the same as the Mark-clear algorithm, however, the subsequent steps do not directly clean the recyclable objects, but move all the surviving objects to one end, and then directly clear the memory outside the end boundary.

 

 

 

Generational collection Algorithm

The basic assumption of GC generation: The Life Cycle of most objects is very short and the survival time is short.

The Generational Collection algorithm divides Java heap into the new generation and the old generation, so that the most appropriate Collection algorithm can be used according to the characteristics of each generation. In the new generation, a large number of objects are found to die each time during garbage collection, and only a small number of objects survive. The replication algorithm is used to complete the collection by paying the copy cost of a small number of surviving objects. In the old age, because the object has a high survival rate and no extra space to allocate a guarantee for it, you must use the "tag-clean" or "tag-sort" algorithm for recovery.

 

Garbage Collector

If the collection algorithm is the method of memory collection, the garbage collector is the specific implementation of memory collection.

 

Serial collector

The serial collector is the oldest, most stable, and highly efficient collector. It may cause a long pause and only one thread is used for collection. Serial collection is used for The new generation and The old generation. The new generation replication algorithm and The old generation mark-compression are used. During garbage collection, The World is stopped)

Parameter Control:-XX: + UseSerialGC serial collector

 

ParNew collector

The ParNew collector is actually a multi-threaded version of the Serial collector. New Generation concurrency, serial in old generation; New Generation replication algorithm, old generation tag-compression

Parameter Control:-XX: + UseParNewGC ParNew collector

-XX: ParallelGCThreads limits the number of threads

 

 

Parallel collector

The Parallel Scavenge collector is similar to the ParNew collector. The Parallel collector focuses more on the system throughput. You can enable the adaptive adjustment policy through parameters. The virtual opportunity Collects performance monitoring information based on the current system running conditions and dynamically adjusts these parameters to provide the most appropriate pause time or maximum throughput; you can also use parameters to control the GC time in milliseconds or proportions. The new generation replication algorithm and old generation tag-compression

Parameter Control:-XX: + UseParallelGC uses the Parallel collector + Old Generation serial

Parallel Old collector

Parallel Old is an Old version of the Parallel Scavenge collector. It uses multithreading and the "mark-Arrangement" algorithm. This collector is provided only in JDK 1.6.

Parameter Control:-XX: + UseParallelOldGC using Parallel collector + parallelism in old age

 

CMS collector

The CMS (Concurrent Mark Sweep) collector is a collector designed to obtain the minimum recovery pause time. At present, a large part of Java applications are concentrated on the internet site or the server of the B/S system. Such applications pay special attention to the response speed of services and hope that the system will have the shortest pause time, to provide a better user experience.

From the name (including "Mark Sweep"), we can see that the CMS collector is implemented based on the "Mark-clear" algorithm, and its operation process is more complex than the previous collectors, the entire process is divided into four steps, including:

Initial mark (CMS initial mark)

Concurrent mark (CMS concurrent mark)

Re-mark (CMS remark)

Concurrent cleanup (CMS concurrent sweep)

The initial tag and re-tag steps still require "Stop The World ". The initial tag only indicates the objects that can be directly associated with GC Roots. The initial tag is fast. The concurrent tag stage is the process of performing GC Roots Tracing, the remarking stage aims to modify the marking records of the part of objects whose tags are changed due to the continued operation of the user program during the concurrent marking period, the pause time of this phase is generally a little longer than the initial marking stage, but far shorter than the concurrency marking time.
The collector thread can work with the user thread in the Process of the longest time-consuming concurrent mark and concurrent clear, so in general, the memory Recycle Process of the CMS collector is executed concurrently with the user thread. Collector of old generation (ParNew generation)

Advantages: Concurrent collection and low pause

Disadvantage: the throughput is reduced when a large amount of space fragments are generated and the concurrency phase is used.

Parameter Control:-XX: + UseConcMarkSweepGC use CMS collector

-XX: + UseCMSCompactAtFullCollection after Full GC, perform a fragment. The sorting process is exclusive and will cause a longer pause.

-XX: + CMSFullGCsBeforeCompaction

-XX: ParallelCMSThreads sets the number of CMS threads (generally equal to the number of available CPUs)

 

G1 collector

G1 is currently one of the most cutting-edge achievements in technological development. The mission assigned by the HotSpot development team is to replace the CMS collector released in jdk1.5. Compared with CMS collectors, G1 collectors have the following features:

1. Space integration. The G1 collector uses the tag Sorting Algorithm and does not produce memory space fragments. When a large object is allocated, the next GC is not triggered in advance because the continuous space cannot be found.

2. predictable pause: This is another major advantage of G1. Reducing the pause time is a common concern of G1 and CMS. However, in addition to pursuing low pause, G1 can also establish a predictable pause time model, users can explicitly specify a time segment with a length of N milliseconds, and the time consumed in garbage collection cannot exceed N milliseconds. This is almost a Real-Time Java (RTSJ) the characteristics of the garbage collector.

As mentioned above, the collection scope of the garbage collector is the entire new generation or old generation, and G1 is no longer like this. When the G1 collector is used, the memory layout of the Java heap is very different from that of other collectors. It divides the entire Java heap into multiple independent regions with the same size (Region ), although there are still concepts of the new generation and the old generation, the new generation and the old generation are no longer physical barriers. They are a set of Region (which can be discontinuous.

 

The new generation collection of G1 is similar to that of ParNew. When the new generation occupies a certain proportion, the collection starts. Similar to CMS, the G1 collector collects objects in the old age for a short pause.

 

Collection steps:

1. During the marking phase, the Initial marking (Initial-Mark) is triggered. This phase is paused and a general Mintor GC is triggered. GC log: GC pause (young) (Incision-mark)

2. Root Region Scanning: During the program running, the same vor zone will be reclaimed (survive until the old age). This process must be completed before young GC.

3. Concurrent Marking: Mark concurrency (and Concurrent application execution) throughout the heap. This process may be interrupted by young GC. In the concurrent tag phase, if all objects in the region object are found to be spam, the region will be immediately recycled (X in the figure ). In addition, during the concurrent marking process, the object activity in each region is calculated (the ratio of the surviving objects in the region ).

 

4. Remark and mark again. There will be a short pause (STW ). The remarking phase is used to collect new garbage from the concurrent marking phase (the concurrent phase runs with the application); G1 uses an initial snapshot algorithm faster than CMS: snapshot-at-the-beginning (SATB ).

5. Copy/Clean up: multiple threads clear inactive objects and STW will exist. G1 copies the surviving objects in the recycle area to the new area, clears the Remember Sets, clears the recycle area concurrently, and returns it to the idle area linked list.

 

 

6. After the copy/clear process. Active objects in the recycle area have been concentrated in the dark blue and dark green areas.

 

 

 

Common collector combinations
  New Generation GC strategy GC policy for the old generation Description
Combination 1 Serial Serial Old Both Serial and Serial Old perform GC in a single thread. This feature is that all application threads are suspended during GC.
Combination 2 Serial CMS + Serial Old CMS (Concurrent Mark Sweep) is a Concurrent GC that achieves Concurrent operations between GC threads and application threads without suspending all application threads. In addition, when CMS fails to perform GC, it will automatically use the Serial Old policy for GC.
Combination 3 ParNew CMS Use the-XX: + UseParNewGC option. ParNew is the parallel version of Serial. You can specify the number of GC threads. By default, the number of GC threads is the number of CPUs. You can use the-XX: ParallelGCThreads option to specify the number of GC threads. If the option-XX: + UseConcMarkSweepGC is specified, the new generation uses the ParNew GC policy by default.
Combination 4 ParNew Serial Old Use the-XX: + UseParNewGC option. The new generation uses the ParNew GC policy, and the Old generation uses the Serial Old GC policy by default.
Combination 5 Parallel Scavenge Serial Old The Parallel Scavenge policy focuses on a controllable throughput: application running time/(application running time + GC time). This ensures that the CPU usage is as high as possible, it is applicable to applications that run permanently in the background, and not to applications with more interactions.
Combination 6 Parallel Scavenge Parallel Old Parallel Old is the Parallel version of Serial Old

 

Combination 7 G1GC G1GC -XX: + UnlockExperimentalVMOptions-XX: + UseG1GC # enable
-XX: MaxGCPauseMillis = 50 # Pause Time target
-XX: GCPauseIntervalMillis = 200 # Pause interval target
-XX: + G1YoungGenSize = 512 m # young generation size
-XX: Region vorratio = 6 # ratio of surviving zones

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.