The foreword 0.

1.Serial garbage collector

1.1 Advantages and disadvantages of Serial garbage collector and applicable scenarios

1.2 Open and use of Serial garbage collector

2. Parnew Garbage Collector

2.1 The pros and cons of the Parnew garbage collector and its applicable scenarios

2.2 Open and use of the Parnew garbage collector

3.Parallel garbage collector

3.1Parallel Garbage Collector pros and cons and applicable scenarios

3.2Parallel Garbage Collector enabled and used

4.CMS Garbage Collector

4.1 Advantages and disadvantages of CMS garbage collector and applicable scenarios

4.2 Open and use of CMS Garbage Collector

4.3 Precautions for the use of CMS Garbage Collector

5.G1 Garbage Collector

5.1 Advantages and disadvantages of the G1 Garbage Collector and applicable scenarios

5.2 Open and use of G1 Garbage Collector

6. Garbage collector algorithm summary

The foreword 0.

We were beforeDeep understanding of JVM (V) — Garbage collection algorithmsVarious garbage collection algorithms have been introduced in, butGC algorithm is the theory of memory recovery, and garbage collector is the implementation of the algorithm. First of all, there is no perfect garbage collector so far,We have to use the appropriate garbage collector for the right scenario.

Serial Garbage Collector is the most basic and oldest single-threaded garbage collector. Let’s look at its garbage collection process diagram first.

Execution flow: Suppose our Java process has run out of heap memory. When THE Serial garbage collector starts, it stops all user threads, reaches a stop-the-world (with a long pause) state, and waits until THE garbage collection is complete before running THE user thread to work.

Serial collector is the oldest, the most stable and the most efficient collector, using only a garbage collector to recycling creates a longer pause in its collection, although want to suspend all other threads, but it is the most simple and efficient, for limited single CPU environment, no thread interaction overhead can obtain the highest single-threaded garbage collection efficiency.

Advantages: Simple implementation, stable, highest single-thread efficiency Disadvantages: There will be a long pause, poor user experience

-XX:+UseSerialGC -XX:+ PrintCommandLineFlagsWhen starting a service, look at the default JVM parameters used by the program

When enabled, a combination of Serial(Young)+Serial(Old) is used. The new generation adopts the copy algorithm, and the old age adopts the mark sorting algorithm.

When we enter the above parameters into IDEA, on the first line of starting the service, we will see that we have started Serial Garbage Collector.

The Parnew garbage collector is a multithreaded version of Serial garbage collector, otherwise acting exactly like Serial garbage collector. Parnew garbage collector also needs to pause all worker threads during garbage collection.

2.1 The pros and cons of the Parnew garbage collector and its applicable scenarios

Advantages:The implementation is simple, stable, in the case of multi-CPU, more efficient than single thread, short pause time

Disadvantages:There will also be certain pauses, the user experience is poor

Applicable scenario:Multiple CPUs, the pursuit of pause time, the need for fast response scenarios, such as Internet applications

-XX:+UseParNewGC -XX:+PrintCommandLineFlags When starting the service, look at the default JVM parameters used by the program

When enabled, a combination of ParNew(Young)+Serial(Old) is used. The new generation adopts the copy algorithm, and the old age adopts the mark sorting algorithm.

3.Parallel garbage collector

Parallel garbage collector is similar to the Parnew garbage collector, another new generation garbage collector that uses a replication algorithm. It is also a Parallel multithreaded garbage collector, but its focus is on achieving manageable throughput (throughput: Ratio of time spent by CPU running user code to total time consumed by CPU) (Throughput formula: time spent by user code/(time spent by user code)+ (time spent by garbage collection))

For example, when the program runs for 100 minutes and the garbage collector runs for 1 minute, the throughput is 99%.

3.1Parallel Garbage-Collecting Pros and Cons Advantages: Multi-threaded collection is fast and throughput can be controlled Disadvantages: If parameters are set too small, switching between threads means additional overhead, thus garbage collection and the total time of user threads can be prolonged. Usage scenarios: multiple CPUs requiring high throughput, such as background computing applications

When Parallel garbage collector is turned on -XX:+UseParallelGC -XX:+ PrintCommandLineFlagsWhen the service is started, look at the default JVM parameters used by the program

Because the Parallel garbage collector controls throughput, there are several important parameters.

-XX: + UseAdaptivesizePolicy sets the Parallel Scavenge collector to have an adaptive adjustment policy. In this mode, parameters such as the size of the young generation, the ratio of Eden to Survivor, and the age of objects promoted to the old generation are automatically adjusted to reach an equilibrium point between heap size, throughput, and pause time.

In cases where manual tuning is difficult, this adaptive approach can be used directly, specifying only the maximum heap of the virtual machine, the target throughput (GCTimeRatio), and the pause time (MaxGCPauseMillis), and letting the virtual machine do the tuning itself.

-XX: ParallelGCThreads sets the number of threads in the young generation parallel collector. In general, it is best to equal the number of CPUs to avoid the excessive number of threads affecting garbage collection performance. 88 By default, when the number of CPUs is less than 8, the value of ParallelGCThreads is equal to the number of CPUs. When the number of CPUs is greater than 8, the number of threads is 3 + ((5*CPU_Count) /8).

-XX: MaxGCPauseMillis sets the garbage collector’s maximum pause time (that is, STW time). This is in milliseconds. In order to keep the pause time within MAXGCPauseMillis as much as possible, the collector adjusts the Java heap size or other parameters as it works.

For the user, the shorter the pause, the better the experience. But on the server side, we focus on high concurrency, overall throughput. So the server side is suitable for Parallel control.

This parameter is used with caution.

-XX: GCTimeRatio: Value range (0,100) The ratio of garbage collection time to total time (=1 / (N + 1)) is used to measure throughput. The default value is 99, which means that the garbage collection time is no more than 1%. The larger the maxGCPausemillis, the higher the ratio.

CMS (Concurrent Mark Sweep: Concurrent Mark Sweep) is a collector that aims to minimize the collection pause time. Its garbage collection thread executes together with the user thread to minimize STW time, using a mark-and-sweep algorithm.

As can be seen from the figure, the CMS garbage collector is divided into four steps: initial mark: need to stop the world; use the mark of the reachabability analysis algorithm; fast concurrent mark: multiple threads concurrently concurrent mark; re-mark: correct the change during concurrent mark because the user program continues to operate concurrent clean: Concurrent purge

4.1 CMS garbage collector advantages and disadvantages and applicable scenarios advantages: concurrent collection, low pause faults: sensitive to CPU resources, unable to deal with the floating garbage, based on the tag removal, generates fragments Applicable scenario: suitable for big heap memory, CPU cores many server applications, this type of application and attach importance to the server response speed, pause time shortest hope system.

-XX:+UseConcMarkSweepGC -XX:+ PrintCommandLineFlagsWhen starting a service, look at the default JVM parameters used by the program

1. Because of concurrent execution, CMS will increase the heap memory footprint when the collection is executed at the same time as the application thread. In other words, the CMS garbage collector must complete the garbage collection before the old heap memory runs out. Otherwise, the CMS garbage collector fails to collect, and the guarantee mechanism will be triggered. The serial old garbage collector will perform a collection in the manner of STWGC, causing a large amount of pause time.

2. The tag scavenging algorithm is unable to defragment, and the old age will run out of memory over time. Finally, the heap memory has to be compressed by guarantee mechanism. CMS also provides parameters – XX: CMSFullGCsBeForeCompation to specify how many times the CMS after garbage collection, a compression of GC.

Before looking at the G1 collector, let’s take a look at G1 by summarizing what previous garbage collectors have in common. The young and old generations are separate and contiguous blocks of memory. Eden +S0+S1 was used for the replication algorithm of the young generation collection. The old age collector must scan the entire old age area and is designed to perform GC as little and as quickly as possible.

At this point, let’s look at G1: G1 is used in multi-processor and large-memory environments to achieve high throughput while meeting the garbage collector pause time requirements as much as possible. In addition, it has the following features:

Like the CMS garbage collector, it can execute concurrently with the worker thread. It’s faster to tidy up space. You don’t want to sacrifice a lot of throughput. No larger Java Heap is required.

The G1 garbage collector, which was originally intended to replace the CMS garbage collector, is better than CMS in the following aspects. G1 is a mark-and-collate algorithm that does not generate much memory fragmentation. G1 can make full use of the advantages of multi-CPU hardware and shorten STW time. On the macro level, G1 does not distinguish between the new generation and the old generation, and divides the memory into several independent sub-regions. You can think of it as the checkerboard pattern of Go. The entire area of memory within the G1 collector is mixed together, but itself still differentiates between the young and the old on a small scale. G1 is also a generational collector, but the entire memory partition is not physically isolated, and each area is converted between old and new as the object changes.

The G1 roughly splits up the memory as shown in the figure

Each area also changed from the original:

If there is not enough memory in the Eden region, some objects will be promoted to the Survivor region. If there is not enough memory in the Survivor region, the bytes will enter the old age.

Execution process: same as CMS Initial flag: Need to stop the world, use the flag of the reachable analysis algorithm, fast Concurrent flag: Multiple threads concurrently concurrent flag Relagging: Correct changes during concurrent flag because the user program continues to operate concurrent purge: Concurrent purge

5.1 Advantages and disadvantages of G1 Garbage Collector and applicable scenarios Advantages: G1 does not generate memory fragmentation; G1 is efficient; G1 can accurately control pauses. Disadvantages: G1 requires a memory set (specifically, a table of cards) to record references between the new and old generations, a data structure that takes up a lot of memory in G1, perhaps 20% or more of the total heap memory capacity. Moreover, the cost of maintaining memory sets in G1 is higher, which brings higher execution load and affects efficiency.

5.2G1 Garbage Collector Enable and Use -XX:+UseG1GC Enable G1 Collector -XX:+PrintCommandLineFlags View the default JVM parameters used by the program when starting the service

In addition, G1 has the following auxiliary parameters.

-XX:G1HeapRegionSize=n: Sets the size of the G1 region, the value is a power of 2, and the range is 1MB~32MB

-XX:MaxGCPauseMillis GC maximum pause time, in milliseconds

– XX: InitiatingHeapOccupancyPercent: heap usage trigger GC, when I was how many defaults to 45

-XX:ParallelGCThreads STW during the number of parallel GC threads

-XX:G1ReservePercent defaults to 10%. In other words, the older generation will reserve 10% of the space for the younger generation to be promoted. Set the percentage of free space reserved for memory to reduce OOM risk.

6 Garbage collector algorithm summary

parameter The new generation of garbage collectors New generation algorithm Old garbage collector Old age algorithm
-XX:+UserSerialGC SerialGC copy SerialOldGC Tag to sort out
-XX:+UseParNewGC ParNew copy SerialOldGC Tag to sort out
-XX:+UseParallelGC Parallel copy ParallelOld Tag to sort out
-XX:+UseConcMarkSweepGC ParNew copy CMS+SerialOld Mark clear
-XX:+UseG1GC As a whole, G1 adopts the marker-collate algorithm Local is a replication algorithm and does not produce fragmentation

Conclusion: Today we introduced the characteristics of various garbage collectors, collection process, collection algorithm and use scenarios, I hope we can use more, master the garbage collector.