Welcome to github.com/hsfxuebao/j… , hope to help you, if you feel ok, please click on the Star

From: www.cnblogs.com/xjwhaha/p/1…

1. Marking stage algorithm

In simple terms, garbage collection is divided into two steps, the first step is to find the garbage, the second step is to recycle, and the algorithm used in the tagging phase is to find out who the garbage is

  1. Almost all Java object instances are stored in the heap, and before the GC can perform garbage collection, it first needs to distinguish between alive and dead objects in memory.
  2. Only objects marked as dead are freed by GC during garbage collection, so this process can be referred to as the garbage marking phase.
  3. So how exactly do you mark a dead object in the JVM? Simply put, an object is declared dead when it is no longer referenced by any living object.
  4. There are two ways to judge the survival of objects: reference counting algorithm and reachability analysis algorithm.

1.1 Reference Counting Algorithm

  1. The Reference Counting algorithm is relatively simple and stores a Reference counter attribute of an integer for each object. Used to record when an object is referenced.
  2. For an object A, if any object references A, then A’s reference counter is incremented by 1. When a reference is invalid, the reference counter is decayed by one. As long as the reference counter of object A has A value of 0, it indicates that object A can no longer be used and can be reclaimed.

Advantages:

  • The implementation is simple and the garbage object is easy to identify.
  • High judgment efficiency and no delay in recovery.

Disadvantages:

  1. It requires separate fields to store counters, which adds to the storage overhead.
  2. Each assignment requires updating the counter, along with addition and subtraction, which adds time overhead.
  3. A serious problem with reference counters is that they cannot handle circular references. This is a fatal flaw that results in Java

Because of the seriousness of the third point, this type of algorithm is not used in the JAVA garbage collector.

What is a circular reference

In the figure above, object one refers to object two, object two refers to object three, and object three refers back to object one,

Object one is referenced externally, so its counter is 2,

However, when the external reference is broken, the counter is reduced by 1, still 1, and will not be cleared, causing the three objects to be unable to be cleared and causing a memory leak

Use code to prove that reference counting algorithms are not used in JAVA

Public class RefCountGC {private byte[] bigSize = new byte[5 * 1024 * 1024]; private byte[] bigSize = new byte[5 * 1024 * 1024]; //5MB Object reference = null; public static void main(String[] args) { RefCountGC obj1 = new RefCountGC(); RefCountGC obj2 = new RefCountGC(); obj1.reference = obj2; obj2.reference = obj1; obj1 = null; obj2 = null; Can obj1 and obj2 be collected? // System.gc(); }}Copy the code

Memory schematic of the code above:

Let’s run this to verify

JVM parameters: -xx :+PrintGCDetails Prints GC logs

Without garbage collection: 16798K used

Manual GC: only 655K is left, indicating that the two objects were indeed reclaimed

Summary of reference counting

  1. Reference counting algorithms are the recycle of choice in many languages, such as Python, which has become more popular due to artificial intelligence and supports both reference counting and garbage collection.
  2. Which is optimal depends on the scenario, and there are large-scale attempts to retain only reference counting mechanisms in practice to improve throughput.
  3. Java did not choose reference counting because of the basic difficulty of handling circular reference relationships. How does Python solve circular references?
    • Manual dereference: It is understood that the code is manually dereferenced when appropriate.
    • Use weakreference WeakRef, a standard library provided by Python that is designed to address circular references.

1.2 Accessibility analysis algorithm

Reachability analysis algorithm: also known as root search algorithm, traceable garbage collection

  1. Compared with reference counting algorithm, reachability analysis algorithm not only has the characteristics of simple implementation and efficient execution, but also can effectively solve the problem of cyclic reference in reference counting algorithm and prevent the occurrence of memory leakage.
  2. In contrast to the reference counting algorithm, the reachability analysis is chosen by Java and C#. This type of Garbage Collection is often called Tracing Garbage Collection

The basic idea is as follows:

  1. The reachability analysis algorithm takes the root object set (GCRoots) as the starting point and searches whether the target object connected by the root object set is reachability from top to bottom.
  2. After using the reachability analysis algorithm, the living objects in memory are directly or indirectly connected by the root object set, and the path searched is called the Reference Chain.
  3. If the target object is not connected by any reference chain, it is unreachable, which means that the object is dead and can be marked as a garbage object.
  4. In the reachability analysis algorithm, only the objects that can be connected directly or indirectly by the root object set are the viable objects.

Schematic diagram:

What elements can GC Roots be

List:

  1. Objects referenced in the virtual stack, such as parameters, local variables, etc. used in methods called by individual threads.
  2. An object referenced by a static property of a class in the method section of a JNI (commonly referred to as a local method) reference in the local method stack, such as a Java class reference type static variable
  3. An object that is referenced by a constant in a method area, such as a reference to a pool of string constants
  4. All objects held by synchronized
  5. Internal references of the Java VIRTUAL machine.
  6. Class objects corresponding to basic data types, some resident exception objects (NullPointerException, OutofMemoryError), system Class loaders.
  7. Jmxbeans that reflect Java virtual machine internals, callbacks registered in JVMTI, local code caches, and so on.

In conclusion, some structures other than heap space, such as virtual machine stack, local method stack, method area, string constant pool, etc. can be used as GC Roots for reachabability analysis

Extension:

In addition to these fixed COLLECTION of GC Roots, other objects can be added “temporarily” to form a complete collection of GC Roots, depending on the garbage collector selected by the user and the memory region currently reclaimed. For example: in the case of generational collection and partial recovery (PartialGC).

If you do garbage collection for only one area of the Java heap (for example: Typical only for the new generation), it must be considered that the objects in this region are completely likely to be referenced by objects in other heap regions, such as the old age, etc. At this time, it is necessary to add the associated regional objects into GC Roots collection to ensure the accuracy of the accessibility analysis.

Conclusion:

  • During the accessibility analysis, the target area should be isolated. Generally, objects outside the target area are taken as GC Roots.
  • For example, when most GC collects the entire heap space, objects outside the heap, such as method areas, are used as objects for GC Roots
  • If the Cenozoic generation is collected separately in a special GC, it is necessary to consider all the objects in the area excluding the Cenozoic generation. For example, the Cenozoic object is referenced in the old age, and the old age object can also be used as GC Roots

Notes for accessibility analysis

  1. If a reachability analysis algorithm is used to determine whether memory is retrievable, the analysis must be performed in a consistent snapshot. If this is not satisfied, the accuracy of the analysis results cannot be guaranteed.
  2. This is also an important reason why GC must “Stop The World”. Even CMS collectors, which claim to be (almost) non-pausing, are required to pause when enumerating root nodes.

Back to the top

2. Object finalization mechanism

  1. The Java language provides an object finalization mechanism that allows developers to provide custom processing logic for objects before they are destroyed.
  2. When the garbage collector finds that there is no reference to an object, that is, before garbage collection of the object, the Finalize () method of the object is always called in the tag phase.
  3. The Finalize () method allows to be overridden in subclasses for resource release when objects are reclaimed. This method usually does some resource freeing and cleaning, such as closing files, sockets, and database connections.

Note that the finaliza() method is not necessarily called before destruction; it is also a determinant of whether the object can be destroyed, called during the marking phase

Object class finalize() source code

Protected void finalize() throws Throwable {}Copy the code

2.1 Precautions for using finalize()

  1. Never call the Finalize () method of an object actively. Instead, let the garbage collector call it.

    • The Finalize () method can cause objects to be resurrected in the tagging phase, but if it is executed manually, then it will not determine (Finalize method can only be called once)
    • The execution time of Finalize () method is not guaranteed. It is completely determined by GC thread. In extreme cases, if GC does not happen, Finalize () method will have no chance to execute. Because there is a thread in the JVM that specifically executes the object Finalize method, the thread has a low priority. Even if the method is called actively, it will not be directly collected
  2. A bad finalize() can seriously affect GC performance (write multiple loops, which can be executed when each object is called at tag time).

  3. In terms of function, finalize() method is similar to the destructor in C++, but Java adopts automatic memory management mechanism based on garbage collector, so finalize() method is fundamentally different from the destructor in C++.

2.2 Three possible states of an object

Objects can be resurrected by finalize() method, so there are three possible states for objects ina virtual machine.

If an object is unreachable from all root nodes, it is no longer in use. In general, this object needs to be reclaimed.

In fact, they don’t have to die. They’re on probation. An unreachable object may “resurrect” itself under certain conditions, and if so, it does not make sense to recycle it immediately

To do this, define three possible states for objects in the virtual machine. As follows:

  1. Accessible: This object can be reached from the root node.
  2. Resurrectible: All references to objects are released, but objects may be resurrected in Finalize (). (All references are released, first marked)
  3. Untouchable: When finalize() of objects is called, GC Roots does not re-reference itself with the object of the node (there is no relationship between the locked object), so there is no resurrection, and then the object will enter the untouchable state. Untouchable objects cannot be resurrected, because Finalize () will only be called once. (Finalize method does not resurrect itself, second mark)

The above three states are distinguished by finalize() method. It can only be reclaimed if the object is marked twice and not reachable.

2.3 Finalize () Specific implementation process

As mentioned in the previous section, determining whether an object objA is recyclable requires at least two marks:

  1. The first mark is made if the object objA to GC Roots has no chain of references.
  2. Filter to determine if this object needs to be finalize()
    • If the object objA does not override the Finalize () method, or if the Finalize () method has already been called by a virtual machine, then the virtual machine considers it “unnecessary to execute” and objA directly determines that it is untouchable. (No relationship, or relationship already found)
    • If the object objA overrides the Finalize () method and has not yet executed it, then the object will be inserted into the F-Queue and its Finalize () method will be triggered by a low-priority Finalizer thread automatically created by the virtual machine. (If there is a possibility of a connection and no search is made, put them all in a room and have them make phone calls.)
  3. The Finalize () method is the last chance for objects to escape death, and objects in the F-queue are later marked a second time by GC. If objA is linked to any object in the reference chain in the Finalize () method, then on the second markup, objA is removed from the “to be collected” collection. (If you find a phone connection, then resurrect)
  4. After that, if the object appears again where no reference exists. In this case, the Finalize () method will not be called again, and the object will directly become the untouchable state, that is, the Finalize () method of an object will only be called once. (If after the resurrection, again closed in, will not let him find a relationship, directly marked the second time)

Use code to prove the above points

In the following code, we use class variables as GC Roots and save ourselves in the Finalize method when objects are collected

public class CanReliveObj { public static CanReliveObj obj; This method can only be called once @override protected void finalize() throws Throwable {super.finalize(); System.out.println(" Call finalize() method overridden by the current class "); obj = this; } public static void main(String[] args) {try {obj = new CanReliveObj(); Obj = null; System.gc(); // Call garbage collector system.out.println (" 1st gc"); // Because Finalizer Thread has a low priority, pause for 2 seconds to wait for thread.sleep (2000); if (obj == null) { System.out.println("obj is dead"); } else { System.out.println("obj is still alive"); } system.out. println(" 2nd gc"); Obj = null; obj = null; System.gc(); // Because Finalizer Thread has a low priority, pause for 2 seconds to wait for thread.sleep (2000); if (obj == null) { System.out.println("obj is dead"); } else { System.out.println("obj is still alive"); } } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code
  • The case of annotating finalize methods

Print:

The first GC obj is deadCopy the code

Indicates that this object is directly reclaimed on the first GC

  • Release comments

Print:

Call the finalize() method overridden by the current class for the first time to gc obj is still alive and the second time to gc obj is deadCopy the code

In the first GC, the Finalize method is called, and the class variable points to itself again, reviving

However, in the second GC, finalize method is not executed any more, and is directly recycled

Back to the top

3. GC Roots tracing

This section describes viewing GC Roots collections using various tools

3.1 Viewing MAT Tools

  1. MAT, short for Memory Analyzer, is a powerful Java heap Memory Analyzer. Used to find memory leaks and view memory consumption.
  2. MAT is based on Eclipse and is a free performance analysis tool.
  3. You can download and use MA at www.eclipse.org/mat/…

Obtain dump file

A snapshot of the JVM’s memory, which can be analyzed by various software,

Here’s how to export a running program to dump

public class GCRootsTest { public static void main(String[] args) { List<Object> numList = new ArrayList<>(); Date birth = new Date(); for (int i = 0; i < 100; i++) { numList.add(String.valueOf(i)); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }} system.out. println(" data added, please do: "); new Scanner(System.in).next(); numList = null; birth = null; System.out.println("numList, birth "); system.out. println("numList, birth "); new Scanner(System.in).next(); System. The out. Println (" end "); }}Copy the code

Run the program first, it will block

Method 1: Use jmap for command lines

Method 2: Use JVisualVM

Step 1: Select monitor TAB and click heap Dump

Step 2: Right click Save as

Step 3: Enter the program and continue to capture the second snapshot

This gives us two memory snapshots, one referenced by local variables and one freed

How do I use MAT to view heap memory snapshots

Open MAT, choose File –> Open Heap Dump, and select the Dump File you want to view

Select Java Basics –> GC Roots

After viewing both snapshots, the local variable is no longer GC Roots because it no longer references the object

After the release put:

3.2 JProfiler Tool Usage

Instead of dump files, view real-time run-time programs

View the object types that have the most in the heap in the current program, and see their GC Roots

Go to Live Memory –> All Object to see the most objects In the Heap, and right click on Show Selection In Heap Walker

Select the References TAB on the display screen To view all instances of this type in the heap, then select an object, select the Incoming References option, and click the Show Paths To FC Roots button To pop up and click Ok

Then you can see the GC Roots of the selected object. For example, in the following case, the GC Roots of the object with the string “done adding, please do” is the OUT object because it is printed by System.out.println(” Done adding, please do “)

Analyze OOM using JProfiler

Code:

public class HeapOOM { byte[] buffer = new byte[1 * 1024 * 1024]; //1MB public static void main(String[] args) { ArrayList<HeapOOM> list = new ArrayList<>(); int count = 0; try{ while(true){ list.add(new HeapOOM()); count++; } }catch (Throwable e){ System.out.println("count = " + count); e.printStackTrace(); }}}Copy the code

The above code will result in OOM. You can enable the JVM instruction to automatically generate the dump file when OOM occurs

To run the program, the JVM instructions: – Xms8m – Xmx8m – XX: + HeapDumpOnOutOfMemoryError

The dump file generated in OOM is in the project directory

java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid14608.hprof ...
java.lang.OutOfMemoryError: Java heap space
	at com.atguigu.java.HeapOOM.<init>(HeapOOM.java:12)
	at com.atguigu.java.HeapOOM.main(HeapOOM.java:20)
Heap dump file created [7797849 bytes in 0.010 secs]
count = 6
Copy the code

If you open JProfiler, you’ll find it in superobjects

You can also view the thread that appears in OOM:

Back to the top

4. Garbage removal phase

In the first section above, we talked about how to mark the garbage, so let’s start cleaning the garbage. There are different algorithms for cleaning the garbage, right

The three garbage collection algorithms that are common in the JVM today are

  1. Mark-sweep algorithm
  2. Copying algorithms
  3. Mark-compact algorithm

4.1 Tokens — removal algorithms

Mark-sweep is a very basic and common garbage collection algorithm, which was proposed by J.McCarthy et al in 1960 and applied to Lisp.

Implementation process

When available memory in the heap is exhausted, the entire program (also known as stop the world) is stopped and two tasks are performed, the first is marked and the second is cleared

** flags: The garbage collector starts by referencing the root node and marks all referenced objects. (Here are marked objects that are not garbage)

  • It is usually recorded as reachable in the Header of an object.
  • Note: mark referenced objects, not garbage!!

** Cleanup: The ** garbage collector traverses the heap memory linearly from beginning to end and reclaims an object if it is not marked as reachable in its headers

In the process diagram, first find all reachable objects from the nodes and mark them as “green”. Then go through the whole object list and clear the ones that are not marked as green

What is clearance?

In this case, the address of the object to be cleared is not really empty. Instead, the address of the object to be cleared is reclaimed and stored in the free address list. The next time a new object needs to be loaded, determine whether there is enough space for the garbage location, and if so, overwrite the original address. (Like deleting a computer’s hard drive)

The free list was mentioned when allocating memory for objects:

If the memory is neat

  • Memory is allocated by means of pointer collision

If the memory is not tidy

  • The virtual machine needs to maintain a free list
  • Use the free list to allocate memory

Disadvantages of the mark-clear algorithm

The advantages of the tag clearing algorithm are obvious, easy to understand and implement, but the disadvantages are also obvious

  1. The efficiency of the tag – clearing algorithm is not high
  2. During GC, the entire application needs to be stopped and the user experience is poor
  3. The free memory cleared in this way is discontinuous, resulting in memory fragmentation and the need to maintain a free list

4.2 Replication Algorithm

  1. In order to address the shortcomings of mark-sweep algorithms in garbage collection efficiency, M.L. Insky published a famous paper in 1963, Lisp Garbage Collector CA Lisp Garbage Collector Algorithm Using Serial Secondary Storage.
  2. The algorithms m.L. Insky described in this paper are known as Copying algorithms, which m.L. Insky himself successfully introduced into an implementation of Lisp.

Core ideas:

Will store the object’s memory space is divided into two pieces, using only one piece at a time, when garbage collection, garbage collector also beginning with node traversal, find all the up to object, but is not marked, but direct copies the object to unused memory block, after all are using all the objects in the block of memory, the role of the exchange of two memory, Finally, garbage collection is completed

Schematic diagram:

Copy reachable objects directly to another region. Once you’ve done that, the objects in the from region are no longer useful, and the new generation uses the copy algorithm

Advantages and disadvantages of replication algorithms

advantages

  1. No marking and cleaning process, simple implementation, efficient operation
  2. After copying the past to ensure the continuity of space, there will be no “fragmentation” problem.

disadvantages

  1. The disadvantage of this algorithm is also obvious, that is, it requires twice the memory space.
  2. Because the address of the object has changed, all references to places where the object is used need to change

Matters needing attention

If there are a lot of garbage objects in the system, the number of viable objects to be copied by the replication algorithm is not too large and the efficiency is high. However, if there are very few garbage objects, almost all of them will be copied each time, and then the loneliness will be removed.

Therefore, due to the high frequency and large quantity of garbage collection, 70%-99% of the memory space can be reclaimed at one time, which is cost-effective in the generation of JVMS. So now commercial virtual machines are using this collection algorithm to recycle the new generation.

4.3 Mark-compact (or mark-compact) algorithm

The high efficiency of the replication algorithm is based on the premise of fewer live objects and more garbage objects. This happens a lot in the new generation, but in the old age, it’s more common for most objects to be living objects.

If the replication algorithm is still used, the cost of replication will be high due to the large number of living objects. Therefore, due to the nature of old-time garbage collection, other algorithms need to be used.

The mark-clean algorithm can be used in the old days, but it is not only inefficient, but also generates memory fragmentation after a collection, so JVM designers need to improve on this. The mark-compact algorithm was born.

Around 1970, g.L. Steele, C.J.Chene, D.S. Ise and other researchers published mark-compression algorithms. In many modern garbage collectors, mark-compression algorithms or improved versions of them are used.

Execution process:

  1. The first stage marks all referenced objects from the root node, as in the mark-clearing algorithm
  2. The second stage presses (or collates) all the living objects to one end of memory and displaces them in order. After that, clean up all the space outside the boundary.

Schematic diagram:

Comparison between mark-compression algorithm and mark-clear algorithm

The end result of the mark-sweep-compact algorithm is the same as the memory defragmentation once the mark-sweep-compact algorithm is complete, so it can also be called a Mark-sweep-compact algorithm.

The essential difference between the two is

  • The mark-sweep algorithm is a non-mobile recovery algorithm,
  • Mark-compression is mobile.

And as you can see when the object allocates memory, if the memory area is scattered, you need to access the free list (mark-clear algorithm reclaims the address to the free list).

However, if mark-compression is used, the marked surviving objects are sorted by memory address, and the unmarked memory is cleaned up. This way, when we need to allocate memory for new objects, the JVM only needs to hold the starting address of memory, which is significantly less overhead than maintaining a free list.

Whether or not to move a reclaimed live object is a risky decision with both advantages and disadvantages.

Advantages and disadvantages of mark-compression algorithms

advantages

  1. Eliminating the fragmentation of memory in the mark-clean algorithm, the JVM only needs to hold the starting address of memory when allocating memory to a new object.
  2. Eliminates the high cost of halving memory in the replication algorithm.

disadvantages

  1. In terms of efficiency, the mark-collation algorithm is lower than the copy algorithm and the mark-clear algorithm
  2. When you move an object, you need to adjust the address of the reference if it is referenced by another object
  3. You need to pause the user application throughout the movement. Namely: STW

4.4 VS of the three clearance algorithms

Horizontal and vertical comparison of the three algorithms:

Mark clear

Tag to sort out

copy

rate

medium

The slowest

The fastest

The space overhead

Less (but will pile up debris)

Less (do not accumulate debris)

Usually requires twice as much space as live objects (no shards)

Moving objects

no

is

is

  1. In terms of efficiency, the replication algorithm is the leader, but it wastes too much memory.
  2. In order to take into account the three indicators mentioned above, the mark-collation algorithm is relatively smoother, but its efficiency is not satisfactory. It has one more mark stage than the copy algorithm, and one more memory collation stage than the mark-clean algorithm.

Conclusion: there is no best algorithm, only the most suitable algorithm

4.5 Generational collection algorithm

None of these algorithms can completely replace other algorithms, they all have their own unique advantages and characteristics.

Generational collection algorithm came into being. His goal is not to replace the algorithm above, but to treat it on a case-by-case basis

The generational collection algorithm is based on the fact that different objects have different life cycles. Therefore, objects with different life cycles can be collected in different ways to improve collection efficiency.

Typically, the Java heap is divided into the new generation and the old generation, so that different collection algorithms can be used according to the characteristics of each generation to improve the efficiency of garbage collection.

During the running of a Java program, a large number of objects are generated, some of which are related to business information:

  • For example, Session objects, threads, and Socket connections in Http requests are directly linked to services, so their life cycle is relatively long.
  • But there are some objects, mainly temporary variables generated in the process of running the program, the life cycle of these objects will be relatively short, such as: String object, because of its invariable class characteristics, the system will produce a large number of these objects, some objects can even be recycled only once.

At present, almost all GCS use the generational collection algorithm to perform garbage collection

Each generation features and suitable recycling algorithms

Young Gen

  • Characteristics of the young generation: the area is smaller than that of the old generation, the object life cycle is short, the survival rate is low, and the recycling is frequent.
  • In this case, the recovery of the replication algorithm is the fastest. The efficiency of the replication algorithm depends only on the size of the current living object, so it is suitable for young generation recycling. The problem of low memory utilization of the replication algorithm is alleviated by the two survivor designs in hotspot. (Overall occupancy ratio is small)

Tenured Gen

  • Characteristics of the old age: large area, long life cycle of objects, high survival rate, recycling less frequent than the young generation.
  • In this case, there are a large number of objects with high survival rates, and the replication algorithm becomes obviously unsuitable. It is usually implemented by mark-clean or a mixture of mark-clean and mark-clean.
    • The cost of the Mark phase is proportional to the number of viable objects. It marks alive objects, and the more alive, the slower they mark
    • The overhead of the Sweep phase is positively correlated with the size of the area managed. Traverses all areas that need to be cleared. The larger the area is, the slower it is
    • The overhead of the Compact phase (the collation phase of the markup collation) is proportional to the data of the living object. The more alive you are, the more objects you can sort out, the slower it is

A brief introduction to the CMS collector

  1. Take the CMS collector in HotSpot as an example. CMS is implemented based on Mark-sweep and has a high recycling efficiency for objects.
  2. For the fragmentation problem, CMS uses Serial Old collector based on mark-Compact algorithm as a compensation measure: When memory collection is poor (due to a Concurrent Mode Failure due to fragmentation), Serial Old is used to perform Full GC to defragment Old memory.
  3. The generational idea is widely used by existing virtual machines. Almost all garbage collectors distinguish between the new generation and the old generation

4.6 Incremental Collection Algorithm

With the existing algorithm, the application will be in a Stop the World state during garbage collection. In the Stop the World state, all threads of the application are suspended, suspending all normal work and waiting for the garbage collection to complete.

If garbage collection takes too long, the application will be suspended for a long time, which will seriously affect user experience or system stability. In order to solve this problem, the research on real-time garbage collection algorithm directly led to the birth of Incremental Collecting algorithm.

Basic idea:

  1. If processing all the garbage at once requires a long system pause, alternate the garbage collection thread with the application thread. Each time, the garbage collection thread collects only a small area of memory space, and then switches to the application thread. Repeat until garbage collection is complete.
  2. In general, incremental collection algorithms are still based on traditional mark-sweep and copy algorithms. Incremental collection algorithms allow garbage collection threads to mark, clean, or copy in a phased manner by properly handling conflicts between threads

Using this approach reduces system downtime because application code is also intermittently executed during garbage collection.

Disadvantages:

Because of the consumption of thread switches and context transitions, the overall cost of garbage collection increases, resulting in a decrease in system throughput.

4.7 Partitioning Algorithm

  1. In general, under the same conditions, the larger the heap space, the longer the time required for a GC and the longer the pauses associated with GC.
  2. To better control the pauses generated by GC, reduce pauses generated by a GC by splitting a large memory area into smaller chunks and reasonably reclaiming several cells at a time, rather than the entire heap space, based on the target pause times.
  3. The generation algorithm divides the heap space into two parts according to the life cycle of the object, and the partition algorithm divides the whole heap space into continuous different cells. Each area is used independently and recycled independently. The advantage of this algorithm is that it can control how many cells are recycled at a time.

Back to the top

5. Write at the end

Note that these are just basic algorithmic ideas, the actual GC collector process is much more complex, and the leading edge GC under development is a composite algorithm that can be both parallel and concurrent. The implementation of the various GC collectors will become clear.