Garbage collector

GC classification and performance indicators

Overview of garbage collector

  1. Garbage collectors are not specified in the specification and can be implemented by different vendors and versions of JVMS.
  2. Due to the rapid iteration of JDK versions, Java has spawned numerous GC versions to date.
  3. By analyzing the garbage collector from different perspectives, GC can be categorized into different types.

New features in different Java versions

  1. Syntax level: Lambda expressions, Switch, auto unboxing, enum, generics
  2. API level: Stream API, new date and time, Optional, String, collection framework
  3. Low-level optimizations: JVM optimizations, GC changes, meta-spaces, static fields, string constant pools, etc

Garbage collector classification

According to the number of threads (garbage collection threads), it can be divided into serial garbage collectors and parallel garbage collectors.

  1. Serial collection means that only one CPU is allowed to perform garbage collection at a time, at which point the worker thread is suspended until the garbage collection is complete.
    1. In cases where hardware platforms are not particularly superior, such as single-CPU processors or small application memory, serial collectors can outperform parallel and concurrent collectors. So serial reclamation is applied by default to the JVM in Client mode on the Client side
    2. Parallel collectors produce shorter pause times than serial collectors on more concurrent cpus
  2. In contrast to serial collection, parallel collection can use multiple cpus to perform garbage collection at the same time, thus improving the throughput of the application, although parallel collection is still exclusive and uses a stop-the-world mechanism like serial collection.

According to the working mode, can be divided into parallel garbage collector and exclusive garbage collector.

  1. And the garbage collector works alternately with application threads to minimize application pause time.
  2. Once run, the exclusive Stop the World garbage collector stops all user threads in the application until the garbage collection process is complete.

According to the way of debris treatment, it can be divided into compressed garbage collector and non-compressed garbage collector.

  1. The compressed garbage collector compresses the surviving objects after the collection is complete to eliminate the recovered fragments. Reallocates object space using pointer collisions
  2. Non-compressed garbage collectors do not do this and allocate object space using the free list

According to the working memory interval, it can be divided into young generation garbage collector and old generation garbage collector.

Evaluate the performance metrics for GC

indicators

  1. Throughput: The percentage of total elapsed time spent running user code (total elapsed time = program elapsed time + memory reclaimed time)

  2. Garbage collection overhead: the complement of throughput, the ratio of the garbage collection time to the total elapsed time.

  3. Pause time: The amount of time a program’s worker thread is suspended while garbage collection is being performed.

  4. Collection frequency: How often collection operations occur relative to the execution of the application.

  5. Memory footprint: The amount of memory occupied by the Java heap.

  6. Fast: The time an object takes from birth to being recycled.

  7. Throughput, pause times, and memory footprint all add up to an impossible triangle. The overall performance of all three will get better and better as technology advances. A good collector usually does at most two of these.

  8. Of these three, time out becomes increasingly important. Because more memory footprint becomes more tolerable as hardware evolves, hardware performance improvements also help reduce the impact of collector runtime on the application, which increases throughput. Memory expansion has a negative effect on latency. [Obtaining resources]

  9. In brief, two main points should be taken:

    • throughput
    • The pause time

Throughput

  1. Throughput is the ratio of CPU time spent running user code to total CPU consumption, i.e. Throughput = user code time run/(User code time run + garbage collection time)
    • For example, if the virtual machine runs for 100 minutes and garbage collection takes 1 minute, the throughput is 99%.
  2. In this case, applications can tolerate high pause times, so high-throughput applications have a longer time baseline and fast response is not a concern
  3. Throughput first, which means that STW has the shortest time per unit time: 0.2+0.2=0.4

Pause time

  1. “Pause time” refers to a period of time during which the application thread is paused to allow the GC thread to execute.
    • For example, a 100-millisecond pause time during GC means that no application threads are active during that 100-millisecond period
  2. Pause time priority means keeping the time of a single STW as short as possible: 0.1+0.1 +0.1 +0.1 +0.1 =0.5, but the total GC time can be long

Throughput vs pause time

  1. High throughput is good because it gives the end user of the application the impression that only application threads are doing “productive” work. Intuitively, the higher the throughput, the faster the application will run.
  2. Low pause times (low latency) are better, and from the end user’s point of view, it is always bad for an application to be suspended, whether for GC or other reasons. Depending on the type of application, sometimes even a brief 200-millisecond pause can interrupt the end-user experience. Therefore, it is important to have low pause times, especially for an interactive application (that is, a scenario with a lot of user interaction).
  3. Unfortunately, “high throughput” and “low pause times” are competing goals.
    • If you choose throughput first, you will necessarily need to reduce the frequency of memory collection, but this will result in the GC needing longer pause times to perform memory collection.
    • On the contrary, if the principle of low latency first is selected, then in order to reduce the pause time of each memory reclamation, memory reclamation can only be performed frequently, but this causes the reduction of young generation memory and leads to the decrease of program throughput.
  4. When designing (or using) GC algorithms, we must determine our goals: a GC algorithm can only target one of two goals (i.e. focus only on large throughput or minimal pause times), or try to find a compromise between the two.
  5. Now standard: Reduce pause times when maximum throughput is first

Overview of different garbage collectors

  1. Garbage collection is Java’s signature capability and greatly improves development efficiency. This is of course a hot topic for interviews.
  2. So, what are the common Java garbage collectors?

History of garbage collector

With virtual machines, there is a need for Garbage Collection. This is Garbage Collection, and the corresponding product is called Garbage Collector.

  1. Along with JDK1.3.1 in 1999 came the Serial GC, which was the first GC in Serial mode. The ParNew garbage collector is a multithreaded version of the Serial collector
  2. Parallel GC and Concurrent Mark Sweep GC were released along with JDK1.4.2 on February 26, 2002
  3. Parallel GC became the HotSpot default GC after JDK6.
  4. In 2012, G1 was available in JDK 1.7U4.
  5. In 2017, G1 became the default garbage collector in JDK9, replacing CMS.
  6. Parallel full garbage collection for G1 garbage collector in JDK10 in March 2018, implementing parallelism to improve worst-case latency.
  7. JDK11 was launched in September 2018. Introduced the Epsilon garbage collector, also known as the “no-OP” collector. At the same time, the introduction of ZGC: Scalable low-delay garbage Collector (Experimental)
  8. In March 2019, JDK12 was released. Enhanced G1 to automatically return unused heap memory to the operating system. Meanwhile, Shenandoah GC: Experimental GC with low pause time is introduced.
  9. JDK13 was released in September 2019. Enhanced ZGC to automatically return unused heap memory to the operating system.
  10. In March 2020, JDK14 was released. Delete the CMS garbage collector. Extend ZGC on macOS and Windows

Seven classic garbage collectors[Obtaining resources]

  1. Serial collector: Serial, Serial old
  2. Parallel recyclers: ParNew, Parallel Avenge, Parallel old
  3. Concurrent collector: CMS, G1

The official documentation

The relationship between seven classic recyclers and garbage generation

  1. Cenozoic collectors: Serial, ParNew, Parallel Scavenge;
  2. Collector: Serial old, Parallel old, CMS;
  3. Whole heap collector: G1;

The composition of the garbage collector

  1. There is a line between the two collectors, indicating that they can be used together:

    • Serial/Serial old
    • Serial/CMS (JDK9 deprecated)
    • ParNew/Serial Old (JDK9 obsolete)
    • ParNew/CMS
    • Insane /Serial Old.
    • Parallel Scavenge/Parallel Old
    • G1
  2. Serial Old is the backup plan for Concurrent Mode Failure of CMS.

  3. (red dotted line) Due to maintenance and compatibility testing costs, the combination Serial+CMS and ParNew+Serial Old was declared deprecated in JDK 8 (JEP173) and completely unsupported in JDK9 (JEP214), i.e., removed.

  4. JEP366 insane and Serial Old GC

  5. In JDK14: Delete CMS garbage collector (JEP363)

  6. Why have a lot of collectors? Is one not enough? Because Java is used in many scenarios, mobile, server and so on. Therefore, it is necessary to provide different garbage collectors for different scenarios to improve the performance of garbage collection.

  7. Although we will compare each collector, we are not trying to pick the best one. There is no one-size-fits-all, one-size-fits-all collector, and there is no one-size-fits-all collector. So we chose only the collector that was most appropriate for our specific application.

View the default garbage collector

  1. -xx :+PrintCommandLineFlags: View command line parameters (including the garbage collector used)
  2. Use the command line command: jinfo-flag Process ID of related garbage collector parameters

JDK8

In JDK 8, set JVM parameters

-XX:+PrintCommandLineFlags

-xx :+UseParallelGC indicates that ParallelGC is used by ParallelGC. ParallelGC is used by default with Parallel Old binding

-XX:InitialHeapSize=266620736 -XX:MaxHeapSize=4265931776-XX:+PrintCommandLineFlags -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:-UseLargePagesIndividualAllocation  -XX:+UseParallelGC` </pre>Copy the code

View it by command line command

Command line command

JPS jinfo-flag UseParallelGC process ID jinfo-flag UseParallelOldGC process ID '</pre>Copy the code

A combination of ParallelGC and ParallelOldGC is used by default in JDK 8

[

JDK9

Serial collector: Serial collector

Serial collector: Serial collector

  1. The Serial collector is the most basic and oldest garbage collector. The only option to recycle the new generation before JDK1.3.
  2. The Serial collector is the default new generation garbage collector in Client mode in HotSpot.
  3. The Serial collector performs memory collection using a copy algorithm, Serial collection, and a stop-the-world mechanism.
  4. In addition to the young generation, the Serial collector also provides the Serial Old collector for performing the Old generation garbage collection. The Serial Old collector also uses Serial collection and “Stop the World” mechanisms, but the memory collection algorithm uses a mark-compression algorithm.
  5. Serial Old is the Client insane garbage collector. Serial Old is used as a backup garbage collector to the CMS insane

The collector is a single-threaded collector, “single-threaded” in the sense that it uses only one CPU (serial) or one collection thread to do the garbage collection. More importantly, while it is garbage collecting, it must suspend all other worker threads until it stops The World.

Advantages of Serial collector

  1. Advantages: Simple and efficient (compared to the single-threaded collections of other collectors), Serial collectors can achieve maximum single-threaded collection efficiency in a single-CPU-limited environment because they have no overhead of thread interaction. A virtual machine running in Client mode is a good choice.
  2. In a user’s desktop application scenario, the available memory is generally small (tens of MB to one or two hundred MB), garbage collection can be completed in a relatively short time (tens of ms to more than one hundred ms), and serial collector is acceptable as long as it does not occur frequently.
  3. In the HotSpot virtual machine, use the -xx :+UseSerialGC parameter to specify that both young and old generations use serial collectors.
    • This is equivalent to replacing Serial GC for freshmen and Serial Old GC for seniors

Summary [Access to Resources]

  1. This garbage collector, as you know, is no longer serial. And in the limited single-core CPU can only be used. It’s not even mono anymore.
  2. For highly interactive applications, this garbage collector is unacceptable. Serial garbage collectors are not typically used in Java Web applications.

ParNew collector: Parallel collection

  1. If the Serial GC is a single-threaded garbage collector in the younger generation, the ParNew collector is a multithreaded version of the Serial collector.
    • Par is short for Parallel, New: only deals with the New generation
  2. There is little difference between the two garbage collectors except that the ParNew collector performs memory collection in a parallel collection manner. The ParNew collector also uses the copy algorithm, stop-the-world mechanism, in the younger generation.
  3. ParNew is the default garbage collector for the new generation of many JVMS running in Server mode.

  1. For the new generation, the recycling times are frequent and the parallel method is efficient.
  2. For the old age, the number of recycling is less, using the serial way to save resources. (CPU parallel need to switch threads, serial can save the resources of switching threads)

ParNew collector compared to Serial collector

Q: Since the ParNew collector is based on parallel collection, is it safe to assume that the ParNew collector will be more efficient at collecting than the Serial collector in any scenario?

A: can’t

  1. ParNew collector runs in a multi-CPU environment. Because it can take full advantage of physical hardware resources such as multi-CPU and multi-core, it can complete garbage collection more quickly and improve the throughput of the program.
  2. But in a single CPU environment, the ParNew collector is no more efficient than the Serial collector. Although the Serial collector is based on Serial collection, because the CPU does not need to switch tasks frequently, it can effectively avoid some of the extra overhead associated with multithreaded interactions.
  3. In addition to Serial, only ParNew GC currently works with the CMS collector

Set up ParNew garbage collector

  1. In the program, the developer can manually specify the use of the ParNew collector to perform memory reclamation tasks with the option “-xx :+UseParNewGC”. It means that the younger generation uses the parallel collector without affecting the older generation.
  2. -xx :ParallelGCThreads Limits the number of threads that are enabled by default.

Parallel collector: Throughput first

Parallel Recycle: Throughput is preferred

  1. The younger generation of HotSpot, in addition to having the ParNew collector based on Parallel recycling, also uses copying algorithms, Parallel recycling, and the “Stop the World” mechanism.
  2. So is Parallel collector superfluous?
    • Unlike the ParNew collector, the Parallel Scavenge collector aims to achieve a manageable Throughput. It is also known as a throughput-first garbage collector.
    • The adaptive adjustment strategy is also an important distinction between the Parallel Avenge and ParNew. (Adjust memory allocation dynamically to achieve an optimal throughput or low latency)
  3. High throughput can efficiently use THE CPU time, as soon as possible to complete the operation of the program, mainly suitable for the background operation without too much interaction. Therefore, it is commonly used in server environments. For example, applications that perform batch processing, order processing, payroll, and scientific calculations.
  4. Parallel collector a Parallel Old collector for performing old-age garbage collection was provided in JDK1.6 in place of the Serial Old collector.
  5. The Parallel Old collector uses a mark-compression algorithm, but is also based on Parallel collection and a stop-the-world mechanism.

  1. In application throughput first scenarios, the combination of Parallel collector and Parallel Old collector performs well in server mode memory reclamation.
  2. In Java8, the default is this garbage collector.

Parallel Avenge parameter Settings

  1. -xx :+UseParallelGC Manually specifies the young generation to use the Parallel collector to perform memory reclamation tasks.

  2. -xx :+UseParallelOldGC: Manually specify that older generations are using parallel collection collectors.

    • It applies to the new generation and the old age respectively
    • The above two parameters apply to Cenozoic and old age respectively. Jdk8 is enabled by default. If one is enabled by default, the other will be enabled. (Mutual activation)
  3. -xx :ParallelGCThreads: Sets the number of threads for the young generation of parallel collectors. In general, it is best to match the number of cpus to avoid too many threads affecting garbage collection performance.

    1. By default, when the number of cpus is less than eight, ParallelGCThreads is equal to the number of cpus.
    2. ParallelGCThreads = 3+[5*CPU_Count]/8 when the number of cpus is greater than 8
  4. -xx :MaxGCPauseMillis sets the maximum garbage collector pause time (that is, the time of STW). The units are milliseconds.

    1. To keep pause times within XX:MaxGCPauseMillis as much as possible, the collector adjusts the Java heap size or some other parameter as it works.
    2. For users, 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.
    3. Use this parameter with caution.
  5. -xx :GCTimeRatio Ratio of the garbage collection time to the total time, equal to 1 / (N+1), which measures the throughput.

    1. The value ranges from 0 to 100. The default value is 99, which means the garbage collection time is less than 1.
    2. There is a certain contradiction with the previous parameter -xx :MaxGCPauseMillis. The longer STW pause time, the Radio parameter will easily exceed the set ratio.
  6. -xx :+UseAdaptiveSizePolicy Sets the Parallel Scavenge avenge has an adaptive adjustment policy

    1. 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 adjusted automatically to reach a balance between heap size, throughput, and pause time.
    2. In cases where manual tuning is difficult, you can use this adaptive approach to specify only the maximum heap of the virtual machine, the throughput of the target (GCTimeRatio), and the pause time (MaxGCPauseMillis), and let the virtual machine do the tuning itself.

CMS collector: Low latency

CMS collector

  1. In JDK1.5, Hotspot introduced a garbage collector that could almost be considered revolutionary in the most interactive applications (that is, references for dealing with users) : CMS (Concurrent-mark-sweep) collector, the first truly Concurrent collector in the HotSpot VIRTUAL machine, enables the garbage collector thread to work simultaneously with the user thread for the first time.
  2. The FOCUS of the CMS collector is to minimize the pause time of user threads during garbage collection. The shorter the pause times (low latency), the better the application that interacts with the user, and the better the response speed improves the user experience.
    • At present, a large part of Java applications are concentrated on the server side of Internet sites or B/S systems. These applications pay special attention to the response speed of services and hope to have the shortest system pause time to bring users a better experience. The CMS collector is a good fit for such applications.
  3. CMS garbage collection algorithm uses mark-sweep algorithm and also stop-the-world
  4. Unfortunately, the CMS collector does not work as the Parallel Scavenge collector, which exists in JDK1.4.0 and is not compatible with the insane. The new generation can only choose one of the ParNew or Serial collectors.
  5. Before G1, CMS was widely used. Today, there are still many systems using CMS GC.

Working Principle of CMS (Process)

The whole process of CMS is more complex than the previous collector. The whole process is divided into four main stages, namely the initial marking stage, concurrent marking stage, re-marking stage and concurrent clearing stage. (The main stages involved in STW are: initial marking and re-marking)

  1. Initial-mark phase: In this phase, all worker threads in the program are briefly paused by stop-the-world, and the main task of this phase is simply to Mark objects that GC Roots can be directly associated with. Once the tag completes, all application threads that were suspended will be resumed. Because the directly related object is small, the speed here is very fast.
  2. Concurrent-mark phase: The process of traversing the entire object graph from the directly associated objects of GC Roots. This process is time-consuming but does not require the suspension of the user thread and can be run concurrently with the garbage collection thread.
  3. Re-marking phase: Because in concurrent mark phase, the program will work thread and garbage collection threads run at the same time or cross running, so * * to correct during concurrent tags, tags that changes caused by the user program continue to operate the part of object mark record, * * the pause time of this stage is usually slightly longer than the initial marking phase, It also causes “stop-the-world” to occur, but for a much shorter time than the concurrent marking phase.
  4. Concurrent-sweep phase: This phase removes dead objects judged by the concurrent-sweep phase, freeing up memory. Since there is no need to move live objects, this phase can also be concurrent with the user thread

CMS analysis

  1. Although the CMS collector uses concurrent collection (non-exclusive), it still performs a stop-the-world mechanism to suspend the worker threads in the program during its initialization and re-marking phases, but not for very long. Thus, none of the current garbage collectors do not need stop-the-world at all, but only pause times as short as possible.
  2. Because the most time-consuming concurrent marking and concurrent cleanup phases do not require pauses, the overall collection is low-pause.
  3. In addition, since the user threads are not interrupted during the garbage collection phase, you should also ensure that the application user threads have enough memory available during the CMS collection process. Therefore, the CMS collector does not wait until the old age is almost completely filled, as other collectors do. Instead, the CMS collector starts collecting when the heap memory usage reaches a certain threshold to ensure that the application still has enough space to run while the CMS is working. If the CMS is running without enough memory reserved for the program, there will be a “Concurrent Mode Failure”, at which point the virtual machine will start a fallback: the Serial old collector will be temporarily enabled to restart the old garbage collection, resulting in long pauses.
  4. The GARBAGE collection algorithm of the CMS collector uses the tag clean algorithm, which means that after each collection, some memory fragmentation will inevitably occur because the memory space occupied by the garbage objects that perform the collection is most likely to be discrete chunks. The CMS will not be able to use the Bump the Pointer technique to allocate memory for new objects, and will only be able to select the Free List to allocate memory.

Why don’t CMS adopt mark-compression algorithms?

The answer is simple, because when concurrent cleanup is done, using Compact memory, how do you use the memory used by the user thread? To ensure that the user thread can continue to execute, the resource it is running on is not affected. The Mark Compact is better suited for “Stop the world” scenarios

Advantages and disadvantages of CMS

advantages

  1. Concurrent collection
  2. Low latency

disadvantages

  1. Memory fragmentation occurs, resulting in insufficient space for user threads after concurrent cleanup. In the case that large objects cannot be allocated, the Full GC has to be triggered early.
  2. The CMS collector is very sensitive to CPU resources. In the concurrent phase, it does not cause user pauses, but it does slow down the application and reduce overall throughput by taking up a portion of the threads.
  3. The CMS collector cannot handle floating garbage. A “Concurrent Mode Failure” may occur, resulting in another Full GC. During the concurrent marking stage, the worker thread and garbage collection thread of the program run at the same time or cross each other. If new garbage objects are generated during the concurrent marking stage, CMS will not be able to mark these garbage objects, which will eventually result in the timely collection of these newly generated garbage objects. ** thus, these previously unreclaimed memory Spaces can only be freed on the next GC.

Setting CMS Parameters

  • -xx :+UseConcMarkSweepGC: Manually specifies the use of the CMS collector to perform memory reclamation tasks.

    After this parameter is enabled, -xx :+UseParNewGC is automatically enabled. That is, the combination of ParNew (Young zone) +CMS (Old zone) +Serial Old (Old zone alternative).

  • – XX: CMSInitiatingOccupanyFraction: set the heap memory usage threshold, once reached the threshold, began to recycle.

  1. The default value for JDK5 and previous versions is 68, which means that a CMS collection is performed when the space usage of the older generation reaches 68%. The default value for JDK6 or later is 92%
  2. If memory growth is slow, you can set a slightly larger value. A larger threshold can effectively reduce the trigger frequency of the CMS, and reducing the number of recycle times can significantly improve application performance. Conversely, if your application’s memory usage is growing rapidly, you should lower this threshold to avoid triggering the old serial collector too often. Therefore, this option can effectively reduce the number of Full GC executions.
  • – XX: + UseCMSCompactAtFullCollection: used to specify the execution of the Full after GC to compress the memory space, so as to avoid the generation of memory fragments. The problem, however, is that the pause times become longer because the memory compacting process cannot be executed concurrently.

  • – XX: CMSFullGCsBeforeCompaction: set after how many times perform Full GC to compress the memory space.

  • -xx :ParallelCMSThreads: Sets the number of CMS threads.

  1. ParallelGCThreads (ParallelGCThreads + 3) is the maximum number of threads that the CPU can support. When CPU resources are tight, application performance can be very poor during the garbage collection phase due to the impact of CMS collector threads.

summary

HotSpot has so many garbage collectors, so if someone asks, what is the difference between Serial GC, Parallel GC, and Concurrent Mark Sweep GC?

  1. If you want to minimize memory and parallel overhead, choose Serial GC;
  2. If you want to maximize the throughput of your application, Parallel GC;
  3. If you want to minimize GC interrupts or pauses, select CMS GC.

Changes to CMS in later JDK releases

  1. New JDK9 feature: CMS marked as Deprecate (JEP291)
    • If the CMS collector is enabled with the -xx :+UseConcMarkSweepGC parameter on a HotSpot VIRTUAL machine of JDK9 or later, the user will receive a warning that the CMS will be deprecated in the future.
  2. JEP363 removes the CMS garbage collector,
    • If XX:+UseConcMarkSweepGC is used in JDK14, the JVM does not issue an error, just a warning message, but no exit. The JVM automatically falls back and starts the JVM in the default GC mode

G1 collector: Regionalization generation type

Why do you need G1

Why release Garbage First (G1) GCS when we already have the First few powerful GCS?

  1. The reason is that applications are dealing with more and more large and complex businesses, more and more users, without GC can not ensure the normal operation of the application, and often the STW GC can not keep up with the actual needs, so they constantly try to optimize GC.
  2. The G1 (garbage-first) Garbage collector is a new Garbage collector introduced after Java7 update4, and is one of the most advanced achievements in today’s collector technology development.
  3. At the same time, in order to accommodate today’s expanding memory and increasing number of processors, pause time is further reduced while maintaining good throughput.
  4. The official goal for the G1 is to achieve the highest throughput possible with manageable latency, hence the heavy burden and expectation of a “fully functional collector.”

Why is it called Garbage First(G1)?

  1. Because G1 is a parallel collector, it divides heap memory into a number of unrelated regions (physically discontinuous). Use different regions to represent Eden, Survivor 0, Survivor 1, old age, and so on.
  2. The G1 GC systematically avoids region-wide garbage collection across the entire Java heap. G1 tracks the value of garbage accumulation in each Region (the amount of garbage collection space obtained and the experience value of garbage collection time), maintains a priority list in the background, and collects garbage from the Region with the highest value according to the allowed collection time.
  3. Since this approach focuses on regions where the most Garbage is collected, we gave G1 a name: Garbage First.
  4. Gbage-first (G1) is a Garbage collector for server applications. It is mainly aimed at machines equipped with multi-core CPUS and large memory capacity. It can meet the GC pause time with a high probability and has high throughput.
  5. In JDK1.7 version officially enabled, remove the identification of Experimental, is the default garbage collector after JDK9, replacing CMS collector and Parallel+Parallel Old combination. Officially called “full-featured garbage collector” by Oracle **.
  6. Meanwhile, CMS has been marked as deprecated in JDK9. G1 is not yet the default garbage collector in JDK8 and needs to be enabled using -xx :+UseG1GC.

Advantages of the G1 collector

Compared to other GC collectors, G1 uses an entirely new partitioning algorithm, which features the following:

  1. Concurrency and parallelism
    • Parallelism: G1 can have multiple GC threads working at the same time during collection, effectively leveraging multi-core computing power. At this point the user thread is STW
    • Concurrency: G1 has the ability to alternate execution with the application, so that some work can be performed at the same time as the application, so that, generally speaking, the application does not completely block during the entire reclamation phase
  2. Generational collection
    • In terms of generation, G1 is still a generational garbage collector. It differentiates the young generation from the old generation, and the young generation still has Eden and Survivor zones. However, from the structure of the heap, it does not require the whole Eden area, the young generation or the old generation to be continuous, nor does it insist on fixed size and fixed quantity.
    • The heap space is divided into regions that contain logical young and old generations.
    • Unlike previous recyclers, it takes care of both the young and the old. Compare other recyclers, either working in the younger generation or working in the older generation;

So G1 is not going to look like this anymore

The G1 partition is such a region

Spatial integration

  1. CMS: “mark-clean” algorithm, memory fragmentation, defragmentation after several GC
  2. The G1 divides memory into regions. Memory reclamation is based on region. Region to Region is a copy algorithm, but overall can actually be regarded as a mark-compact algorithm, both algorithms can avoid memory fragmentation. This feature helps programs run for a long time and allocate large objects without triggering the next GC prematurely because contiguity memory space cannot be found. This is especially true when the Java heap is very large.

Predictable pause time model

Predictable pause time model (i.e., soft real-time soft real-time)

This is another advantage G1 has over CMS. In addition to pursuing low pauses, G1 also models predictable pause times, allowing users to explicitly specify that no more than N milliseconds should be spent on garbage collection within a time segment of M milliseconds.

  1. Due to partitioning, G1 can select only part of the region for memory reclamation, which reduces the scope of reclamation, so that the occurrence of global pause can be well controlled.
  2. G1 tracks the value of garbage accumulation in each Region (the amount of garbage collection space obtained and the experience value of garbage collection time), maintains a priority list in the background, and collects garbage from the Region with the highest value according to the allowed collection time. The G1 collector is guaranteed to achieve the highest possible collection efficiency in a limited time.
  3. G1 is not necessarily as good at delaying pauses as CMS GC is at best, but much better at worst.

Disadvantages of the G1 collector

  1. Compared to CMS, G1 does not have a comprehensive, overwhelming advantage. For example, G1 has a higher garbage collection Footprint and overload than CMS during user program execution.
  2. Empirically, CMS is more likely to outperform G1 in small memory applications, while G1 is more likely to outperform G1 in large memory applications. The balance point is between 6-8GB.

G1 Parameter Settings

  • -xx :+UseG1GC: Manually specifies the use of the G1 garbage collector to perform memory collection tasks
  • -xx :G1HeapRegionSize: Set the size of each Region. The value is a power of 2, ranging from 1MB to 32MB, and the goal is to partition about 2048 regions based on the minimum Java heap size. The default is 1/2000 of the heap.
  • -xx :MaxGCPauseMillis: Sets the maximum GC pause time that the JVM will try to achieve, but is not guaranteed to achieve. The default value is 200ms
  • -xx :+ParallelGCThread: Sets the number of STW worker threads. The maximum value is 8
  • -xx :ConcGCThreads: Sets the number of concurrent threads to be tagged. Set n to about 1/4 of the number of parallel garbage collection threads (ParallelGcThreads).
  • – XX: InitiatingHeapOccupancyPercent: set the trigger a concurrent GC cycle Java heap usage rate threshold value. If this value is exceeded, GC is triggered. The default value is 45.

Common steps for the G1 collector

G1 was designed to simplify JVM performance tuning by developers in three simple steps:

  1. Step 1: Start the G1 garbage collector
  2. Step 2: Set the maximum memory for the heap
  3. Step 3: Set a maximum pause time

There are three garbage collection modes available in G1: YoungGC, Mixed GC, and Full GC, which are triggered under different conditions.

Application scenarios of G1

  1. Server – oriented applications for machines with large memory and multiple processors. (No surprise in a normal size heap)
  2. The most important applications are applications that require low GC latency and have a large heap of solutions;
  3. For example, when the heap size is about 6GB or larger, predictable pause times can be less than 0.5 seconds; G1 ensures that each GC pause is not too long by incrementally cleaning only some regions at a time, not all of them.
  4. To replace the CMS collector in JDK1.5; G1 may be better than CMS when:
    • More than 50% of the Java heap is occupied by active data;
    • The frequency of object assignment or chronological lifting varies greatly;
    • GC pauses are too long (longer than 0.5 to 1 second)
  5. In addition to G1, all garbage collectors use built-in JVM threads to perform multi-threaded GC operations. G1 GC can use application threads to perform background GC operations. When the JVM’s GC thread is slow, the system calls application threads to help speed up the garbage collection process.

Partition Region

Partition Region: Divide the whole into parts

  1. When using the G1 collector, it divides the entire Java heap into approximately 2048 independent Region blocks of the same size. Each Region block size is determined by the actual size of the heap, and the overall Region block size is controlled between 1MB and 32MB, and is controlled to the NTH power of 2, namely 1MB, 2MB, 4MB, 8MB, 16MB, and 32MB. Can be achieved by
  2. XX: G1HeapRegionSize is set. All regions are the same size and do not change during the lifetime of the JVM.
  3. Although the concept of Cenozoic and oldyn is still retained, Cenozoic and oldyn are no longer physically separated; they are collections of parts of regions (which do not need to be continuous). Dynamic Region allocation is used to achieve logical continuity.
  4. A Region may belong to an Eden, Survivor, or Old/Tenured memory Region. However, a Region can belong to only one role. In the figure, E indicates that the Region belongs to Eden memory Region, S indicates that the Region belongs to Survivor memory Region, and O indicates that the Region belongs to Old memory Region. Blank Spaces in the figure represent unused memory space.
  5. The G1 garbage collector also adds a new memory region called the Humongous memory region, shown in block H. It is used to store large objects. If the number of regions exceeds 0.5, H is used to store large objects.

Correction: More than 1.5 regions. The G1 Garbage Collector Step by Step

As shown regions can be allocated into Eden, survivor, and old generation regions. In addition, there is a fourth type of object known as Humongous regions. These regions are designed to hold objects that are 50% the size of a standard region or larger. They are stored as a set of contiguous regions. Finally the last type of regions would be the unused areas of the heap.

Translation:

As shown in the figure, regions can be assigned to Eden, Survivor, and Old-time regions. In addition, there is a fourth type of object called a giant region. These regions are designed to accommodate objects 50% or larger of the standard region size. They are stored as a set of contiguous areas. Finally, the last region type is the unused region of the heap.

The reason for setting H

Large objects in the heap are directly assigned to the old age by default, but if it is a short-lived large object it can have a negative impact on the garbage collector. To solve this problem, G1 has a Humongous section, which is dedicated to large objects. If an H block does not fit a large object, G1 looks for contiguous H blocks to store. Sometimes you have to start the Full GC in order to find consecutive H regions. Most of G1’s behavior treats the H region as part of the old age.

The details of the Regio

  1. Each Region allocates space via pointer collisions
  2. G1 sets two Pointers named Top at Mark Start (TAMS) for each Region to divide part of the Region space for the allocation of new objects in concurrent reclamation. The addresses of newly allocated objects must be above these two Pointers.
  3. TLAB is also used to ensure concurrency

G1 garbage collection process

The garbage collection process of G1 GC mainly includes the following three steps:

  • Young GC
  • Concurrent Marking in the old days
  • Mixed GC
  • (Single-threaded, exclusive, high-intensity Full GC will still exist if needed. It provides a fail-safe mechanism against GC evaluation failures, i.e., strong collection.

Clockwise, Young GC – > Young GC+Concurrent Marking – > Mixed GC order

The recycling process

  1. The application allocates memory and starts the young generation reclamation process when the young generation’s Eden area is exhausted. G1’s young-generation collection phase is a parallel, exclusive collector. During the young generation collection period, the G1 GC suspends all application threads and starts multithreading to perform the young generation collection. Then move the surviving object from the young generation to the Survivor or the old, or possibly both.
  2. When heap memory usage reaches a certain value (45% by default), the old-age concurrent marking process begins.
  3. Mark completion to begin the mixed recycling process immediately. For a mixed payback period, the G1 GC moves live objects from the old period to the free period, which becomes part of the old period. Unlike the young generation, the G1 collector of the old generation does not need to recycle the entire old generation, but only scan/reclaim a small number of old regions at a time. At the same time, the old Region is reclaimed along with the young generation.
  4. For example, a Web server with a Java process with a maximum heap memory of 4 gigabytes responds to 1500 requests per minute and allocates about 2 gigabytes of new memory every 45 seconds. G1 does a young generation collection every 45 seconds, with a heap utilization rate of 45% every 31 hours, and begins the old generation concurrent tagging process, followed by four or five mixed collections.

Remembered Set

Talked about before

  1. The problem of an object being referenced by different regions
  2. A Region cannot be isolated. Objects in a Region can be referenced by objects in any Region. Do YOU need to scan the entire Java heap to determine whether an object is alive?
  3. This problem also exists in other generational collectors (and is more pronounced in G1, because G1 focuses on heaps)
  4. Will the new generation also have to scan the old? This reduces the efficiency of the Minor GC

Solutions:

  1. For both G1 and other generational collectors, the JVM uses Remembered Set to avoid full heap scans.
  2. Each Region has a corresponding Remembered Set
  3. Each time a Reference data Write operation is performed, a Write Barrier operation is generated.
  4. Then check whether the Reference to be written refers to an object in a different Region from the Reference type data (other collectors: check whether old objects refer to new ones).
  5. If not, the related references are recorded in the Remembered Set of the Region where the reference points to the object through CardTable.
  6. When garbage collection is performed, add the enumeration scope of the GC root to Remembered Set. You can guarantee that no global scan will be done, and there will be no omissions.

  1. Remembered Set was introduced during Region reclamation to avoid a full heap scan
  2. Remembered Set Records which objects in the current Region are referenced by
  3. This way, when making a Region copy, don’t scan the heap. Just go to Remembered Set to find the object that references the current Region
  4. After the Region copy is complete, modify the references of objects in Remembered Set

G1 recovery process 1: Young generation GC

  1. When JVM starts, G1 prepares Eden area first, and the program continuously creates objects to Eden area during the running process. When Eden space runs out, G1 will start a young generation garbage collection process.
  2. The young generation only collects the Eden area and Survivor area
  3. In YGC, G1 stops The execution of The application stop-the-world first and creates a Collection Set, which refers to The Collection of memory segments that need to be reclaimed. The Collection in The young generation reclamation process contains all memory segments in The Eden area and Survivor area of The young generation.

The picture basically means:

1. After recycling E and S, the remaining objects will be copied to the new S area

2. Zone S can be promoted to Zone O if it reaches a certain threshold

Meticulous process:

Then start the following recycling process:

  1. In the first stage, the roots are scanned

    The root refers to GC Roots, and the root reference along with the external reference of the RSet record acts as an entry point for scanning the living object.

  2. Phase 2, update the RSet

  3. In the third stage, the RSet is processed

    Identify the objects in Eden that are pointed to by the old objects. The objects in Eden that are pointed to are considered alive.

  4. In the fourth stage, objects are copied.

    • At this stage, the object tree is traversed, and the surviving objects in the Eden block memory segment are copied to the hollow memory segment in Survivor block, and surviving objects in Survivor block memory segment
    • If the age does not reach the threshold, the age will be increased by 1, and the threshold will be copied to the hollow memory segment in the Old region.
    • If Survivor space is insufficient, some data in Eden space will be promoted directly to the old space.
  5. The fifth stage deals with references

    Handle Soft, Weak, Phantom, Final, JNI Weak etc references. Finally, the data in Eden space is empty, GC stops working, and the objects in the target memory are continuously stored without fragmentation. Therefore, the replication process can achieve the effect of memory consolidation and reduce fragmentation.

Remark:

  1. For the application’s reference assignment statement oldobject. field (this is old) =object (this is new), the JVM performs special operations before and after to enqueue a card that holds object references in the dirty Card queue. During the recycle of the young generation, G1 will process all cards in the Dirty Card Queue to update the RSet and ensure that the RSet accurately reflects the reference relationship in real time.
  2. Why not update the RSet directly at the reference assignment statement? This is for the sake of performance, RSet processing requires thread synchronization, which can be very expensive, using queue performance is much better.

G1 recovery process ii: Concurrent marking process

  1. Initial marking phase: marking objects directly reachable from the root node. This phase is STW and triggers a young GC. Because this phase is STW, we only scan objects reachable by the root node to save time.
  2. Root Region Scanning: THE G1 GC scans the old Region objects that are directly reachable from the Survivor Region and marks the referenced objects. This must be done before the Young GC, which uses the replication algorithm to GC Survivor areas.
  3. Concurrent Marking:
    1. Concurrent marking (and application concurrent execution) throughout the heap may be interrupted by the Young GC.
    2. During the concurrent marking phase, if all objects in a region object are found to be garbage, the region is immediately reclaimed.
    3. At the same time, the object activity (the percentage of living objects in the region) of each region is calculated during concurrent tagging.
  4. Remark: Because the application is ongoing, the result of the last mark needs to be corrected. Is the STW. G1 uses a snapshot-at-the-beginning (SATB) algorithm that is faster than CMS.
  5. Exclusive cleanup (STW) : Calculates the percentage of live objects and GC collections for each region and sorts them to identify areas that can be mixed for collection. Set the stage for the next phase. Is the STW. This phase does not actually do garbage collection
  6. Concurrent cleanup phase: Identify and clean up completely free areas.

G1 Recovery process 3: Mixed recovery process

When more and more objects are promoted to Old regions, in order to avoid running out of heap memory, the virtual machine will trigger a Mixed garbage collector, namely Mixed GC. This algorithm is not an Old GC, but will reclaim the whole Young Region as well as part of the Old Region. Note here: part of the old era, not all of it. You can select which Old regions to collect, thus controlling the garbage collection time. Also note that Mixed GC is not a Full GC.

Details of mixed recycling

  1. After the concurrent marking ends, the segments that are 100% garbage in the old age are reclaimed and the segments that are partially garbage are calculated. By default, these older memory segments are collected eight times (which can be set to -xx :G1MixedGCCountTarget). A Region is divided into eight memory segments.
  2. The Collection Set of a mixed Collection consists of one-eighth of old age segments, Eden segment, and Survivor segment. The algorithm of hybrid collection is exactly the same as the algorithm of young generation collection, but it collects more memory segments of the old generation. Please refer to the young generation recycling process above for details.
  3. Since memory segments are recycled eight times by default in older generations, G1 prioritises memory segments with more garbage. The higher the percentage of garbage in memory segments, the more garbage will be collected first. There is a threshold that determines whether memory segments are reclaimed. XX: G1MixedGCLiveThresholdPercent, the default is 65%, which means waste of memory block to achieve 65% can be recycled. If the garbage ratio is too low, it means that there is a high percentage of live objects, which will take more time to replicate.
  4. Mixed recycling does not have to be done eight times. There is a threshold -xx :G1HeapWastePercent, which defaults to 10%, meaning that 10% of the total heap memory is allowed to be wasted, meaning that if the percentage of garbage that can be recycled is less than 10% of the heap memory, no mixed recycling is done. Because GC takes a lot of time but recycles very little memory.

G1 Collection optional process 4: Full GC

  1. The G1 was designed to avoid Full GC. But if that doesn’t work, G1 stops The application’s execution (stop-the-world) and uses a single-threaded memory reclamation algorithm for garbage collection, with poor performance and long application pauses.
  2. To avoid Full GC, JVM parameters need to be adjusted once Full GC occurs. When will Ful1GC occur? For example, if the heap is too small, G1 will fall back to Full GC when there is no empty segment available for copying live objects, a situation that can be resolved by increasing memory.

There are two possible reasons for G1 Full GC:

  1. EVacuation without sufficient to-space to hold objects of advancement;
  2. Space runs out before the concurrent processing completes.

G1 supplement

According to official information from Oracle, the Evacuation phase was designed to be executed concurrently with user programs, but this is complicated and is not urgent considering that G1 only returns to part of a Region and the pause times are controlled by the user. ** instead chose to put this feature in the low-latency garbage collector (ZGC) that emerged after G1. ** In addition, considering that G1 is not only geared towards low latency, pausing user threads maximizes garbage collection efficiency, the implementation of pausing user threads completely was chosen to ensure throughput.

Optimization suggestions for G1 collector

  1. Young generation size
    • Avoid explicitly setting the young generation size with related options such as -xmn or -xx :NewRatio, because a fixed young generation size overwrites a predictable pause time target. We leave G1 to adjust itself
  2. Don’t be too strict with your pause time goals
    • The throughput goal for the G1 GC is 90% application time and 10% garbage collection time
    • When evaluating G1 GC throughput, don’t be too harsh with pause time goals. Being too stringent means you are willing to incur more garbage collection overhead, which directly affects throughput.

Garbage collector summary

Comparison of 7 garbage collectors

As of JDK1.8, there are seven different garbage collectors. Each garbage collector has different characteristics, in the specific use of time, need to choose different garbage collectors according to the specific situation.

How do I choose a garbage collector

The configuration of the Java garbage collector is an important choice for JVM optimization, and choosing the right garbage collector can make a big difference in JVM performance. How do I choose a garbage collector?

  1. Prioritizing the heap size allows the JVM to adapt.
  2. If memory is less than 100M, use a serial collector
  3. If it is a single-core, single-machine program, and no pause time requirements, serial collector
  4. If it is multi-CPU, requires high throughput, and allows pause times of more than 1 second, choose parallelism or the JVM’s choice
  5. If you have multiple cpus and are looking for low pause times that require fast responses (such as a delay of no more than 1 second, as in Internet applications), use a concurrent collector
  6. The G1 is officially recommended for high performance. The current Internet projects are basically using G1.

Finally, one point needs to be clarified:

  1. There is no single best collector, and there is no universal collection algorithm
  2. Tuning is always for specific scenarios, specific needs, and there is no one-size-fits-all collector

The interview

  1. When it comes to garbage collection, interviewers can step by step dive into the theoretical and practical aspects of garbage collection, but they don’t necessarily need to know everything. But if you understand the principles, it will be a definite plus in the interview.
  2. Here’s the more general, basic part:
    • What are the algorithms for garbage collection? How do I determine if an object is recyclable?
    • The basic flow of garbage collector work.
  3. Also, pay attention to the various parameters commonly used in the garbage collector chapter

GC Log Analysis

Common Parameter Settings

GC log parameter Settings

By reading GC logs, we can understand the Java virtual machine memory allocation and reclamation policies.

List of parameters for memory allocation and garbage collection

  1. -xx :+PrintGC: prints GC logs. Similar: verbose: gc
  2. -xx :+PrintGCDetails: Prints GC details logs
  3. -xx :+PrintGCTimestamps: prints GC timestamps (in base time)
  4. -xx :+PrintGCDatestamps: outputs the GC timestamp (in the form of a date, for example, 2013-05-04T21:53:59.234 +0800)
  5. -xx :+PrintHeapAtGC: Prints heap information before and after GC
  6. – Xloggc:… /logs/gc.log: output path of log files

verbose:gc

1. JVM parameters

-verbose:gc` </pre>
Copy the code

2. This only shows the total GC heap change as follows:

3. Parameter analysis

PrintGCDetails

1. JVM parameters

-XX:+PrintGCDetails` </pre>
Copy the code

2. Enter the following information

3. Parameter analysis

PrintGCTimestamps and PrintGCDatestamps

1. JVM parameters

-XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps` </pre>
Copy the code

2. The following information is displayed

3, Description: The log with the date and time

Additional notes for GC logs

  1. “[GC” and “[Full GC” indicate The type of pause for this garbage collection, and “Full” indicates that a “Stop The World” GC occurred.
  2. Using Serial collector the name of the New Generation is Default New Generation, so “[DefNew” is displayed.
  3. – The name of the collector using ParNew in the New Generation will change to “[ParNew”, meaning “Parallel New Generation”
  4. Use the Parallel Avenge collector. The Cenozoic insane is called “PSYoungGen.”
  5. The name of the old collection is determined by the collector, just like the new one
  6. Using the G1 collector, it shows “garbage-first heap”
  7. Allocation Failure indicates that this time GC is caused because there is not enough space in the young generation to store new data.
  8. [ PSYoungGen: 5986K->696K(8704K) ] 5986K->704K (9216K)
    • Size of young generation before GC collection, size of young generation after GC collection, (total size of young generation)
    • Parentheses: GC collects the size of the previous young generation and the old generation, and the size after the collection, (total size of the young generation and the old generation)
  9. User indicates the reclaim time in user mode, sys kernel-mode, and real. Due to multi-core thread switching, the total time may exceed real time

Young GC

Full GC

For example,

JAVA
/** * Run * -verbose: gC-xMS20m-XMx20m-xmn10m-xx :+PrintGCDetails -xx :SurvivorRatio= 8-xx :+UseSerialGC * /
public class GCLogTest1 {
    private static final int _1MB = 1024 * 1024;

    public static void testAllocation(a) {
        byte[] allocation1, allocation2, allocation3, allocation4;
        allocation1 = new byte[2 * _1MB];
        allocation2 = new byte[2 * _1MB];
        allocation3 = new byte[2 * _1MB];
        allocation4 = new byte[4 * _1MB];
    }

    public static void main(String[] agrs) {
        testAllocation();
    }
}` </pre>
Copy the code

The situation in JDK7

1. First, we will store three 2M arrays in Eden zone, and then the next 4M arrays will not be able to be stored, because there is only 2M remaining space in Eden zone. Then a Young GC operation will be performed to store the contents of the original Eden zone into Survivor zone. But if the Survivor zone does not fit, it will directly advance to the Old zone

2. Then we store 4M objects into Eden area

There is something wrong with the old pictures. Free should be 4M

Case in JDK8

JAVA
com.atguigu.java.GCLogTest1
[GC (Allocation Failure) [DefNew: 6322K->668K(9216K), 0.0034812 secs] 6322K->4764K(19456K), 0.0035169 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 
Heap
 def new generation   total 9216K, used 7050K [0x00000000fec00000.0x00000000ff600000.0x00000000ff600000)
  eden space 8192K,  77% used [0x00000000fec00000.0x00000000ff23b668.0x00000000ff400000)
  from space 1024K,  65% used [0x00000000ff500000.0x00000000ff5a71d8.0x00000000ff600000)
  to   space 1024K,   0% used [0x00000000ff400000.0x00000000ff400000.0x00000000ff500000)
 tenured generation   total 10240K, used 4096K [0x00000000ff600000.0x0000000100000000.0x0000000100000000)
   the space 10240K,  40% used [0x00000000ff600000.0x00000000ffa00020.0x00000000ffa00200.0x0000000100000000)
 Metaspace       used 3469K, capacity 4496K, committed 4864K, reserved 1056768K
  class space    used 381K, capacity 388K, committed 512K, reserved 1048576K

Process finished with exit code 0` </pre> ! [image- 20210531204906855.](https://upload-images.jianshu.io/upload_images/26558875-cb4ab9a956b68812.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
Copy the code

In contrast to JDK7, JDK8 decides that the 4M array is a large object and then defiles the old area directly

Common log analysis tools

Save log file

JVM arguments: -xloggc :./logs/gc.log,./ indicates the current directory. In IDEA, the current directory where the program is running is the root of the project, not the root of the module

There are several tools available to analyze these GC logs. Common log analysis tools are:

GCViewer, GCEasy, GCHisto, GCLogViewer, Hpjmeter, Garbagecat, etc

Recommendation: GCeasy

The online analysis is at gceasy.io

New developments in garbage collectors

The evolution of the garbage collector

  1. GC is still in rapid development, the current default option G1 GC is constantly improving, many of the shortcomings we previously thought, such as serial Full GC, Card Table scanning low efficiency, have been greatly improved, for example, after JDK10, Fu11GC has been running in parallel, in many scenarios, It also performs slightly better than ParallelGC’s parallel Ful1GC implementation.
  2. Even SerialGC, although relatively old, is not necessarily outdated in its simple design and implementation. Its overhead, no matter GC related data structure overhead or thread overhead, is very small. Therefore, with the rise of cloud computing, in new application scenarios such as Serverless, Serial Gc has found a new arena.
  3. Unfortunately, CMSGC has been deprecated in JDK9 and removed in JDK14, although it still has a very large user base due to theoretical flaws in its algorithm
  4. The G1 collector has been the default collector for several years now. We also saw the introduction of two new collectors: ZGC (JDK11 appearing) and Shenandoah (Open JDK12), which feature low pause times

Shenandoah GC

Shenandoash GC for Open JDK12: Low-pause GC (Experimental)

  1. Shenandoah is undoubtedly the loneliest of the many GC’s. The first Hotspot garbage collector not developed by the Oracle team. Inevitably ostracized by the authorities. For example, Oracle, which claims no difference between openJDK and OracleJDK, still refuses to support Shenandoah in OracleJDK12.
  2. Shenandoah Garbage Collector An implementation of the Pauseless GC, a garbage collector research project originally undertaken by RedHat, was designed to meet the need for low pauses for memory reclamation on the JVM. Contributed to OpenJDK in 2014.
  3. Red Hat’s Shenandoah team claims that the Shenandoah garbage collector pauses regardless of the size of the heap, meaning 99.9% of the time, whether the heap is set to 200MB or 200GB, can limit garbage collection pauses to less than 10 milliseconds. However, actual usage performance will depend on the actual working heap size and workload.

RedHat published a paper in 2016 that tested using ES to index 200GB of wikipedia data. From the results:

  1. The pause time is a qualitative leap compared to other collectors, but it does not achieve the maximum pause time under ten milliseconds.
  2. There was a significant drop in throughput, with the longest total running time of any test collector.

conclusion

  1. Weakness of the Shenandoah GC: Throughput degradation under high operating load.
  2. Shenandoah GC’s strength: low latency.

The shocking and revolutionary ZGC

  1. The official document: docs.oracle.com/en/java/jav…
  2. ZGC is highly similar to Shenandoah’s goal of achieving low latency that limits garbage collection outages to less than 10 milliseconds at any heap size with as little impact on throughput as possible.
  3. The ZGC collector is a garbage collector based on Region memory layout, with (for now) no generation, using techniques such as read barriers, dye Pointers, and memory multiple mapping to implement concurrent mark-compression algorithms, with low latency as the primary goal.
  4. The working process of ZGC can be divided into four stages: concurrent marking – concurrent preparatory reallocation – concurrent reallocation – concurrent remapping, etc.
  5. ZGC is executed almost everywhere concurrently, except for the STW that is initially marked. So the pause time is almost spent on the initial tag, and the actual time for this part is very little.

throughput

Max-jops: data with low latency as the primary premise

Critical-jops: data with low latency is not considered

Low latency

In the pause time test, which the ZGC is strong at, it pulls away two orders of magnitude from the Parallel and G1 without mercy. The ZGC has no trouble keeping average pauses, 95% pauses, 998 pauses, 99.98 pauses, and maximum pause times under 10 milliseconds.

While the ZGC is still in experimental mode and not all features are complete, the performance at this point is impressive enough to be described as “shocking and revolutionary.” The preferred garbage collector for future server-side, large-memory, low-latency applications.

  1. Prior to JDK14, ZGC was supported only by Linux.

  2. Although many users of ZGC use Linux-like environments, they also need ZGC for development deployment and testing on Windows and macOS. Many desktop applications can also benefit from ZGC. As a result, the ZGC feature has been ported to Windows and macOS.

  3. ZGC is now available on MAC or Windows as shown in the following example:

    + UnlockExperimentalVMOptions – – XX: XX: + UseZGC

Heap-oriented AliGC[Obtaining resources]

AliGC is alibaba JVM team based on G1 algorithm, for LargeHeap application scenarios. Comparison in the specified scenario:

In the end, I wish you all success as soon as possible, get satisfactory offer, fast promotion and salary increase, and walk on the peak of life.

If you can, please give me a three support me?????? [Obtain information]