This is the 14th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
What is garbage collection?
Garbage Collection is called Garbage Collection, or GC, and until you really understand GC, you might have thought that GC was created because of the Java language. In fact, garbage collection is much older than Java, going back to Lisp, the first language to use dynamic memory allocation and garbage collection, which was created at MIT in 1960.
There are three things to consider in garbage collection: 1. What memory needs to be reclaimed? 2, when to recycle? 3. How to recycle?
How do I determine if an object is recyclable?
Reference counting method
Reference counting refers to incrementing the reference to an object whenever it is referenced by another variable, incrementing it by two if it is referenced twice, and subtracting it by one if it is not referenced again.
When the reference count of an object is zero, no one references it and the object is considered garbage and can be collected.
The reference counting algorithm used in Python’s early days is not used by the JVM. Instead, the following algorithm is used.
Accessibility analysis algorithm
Let’s start with a noun root object, which refers to objects that are definitely not garbage collected as root objects.
Before garbage collection, all objects in the heap are scanned to determine whether objects in the heap are referenced directly or indirectly by the root object. If so, the object cannot be recycled. If the object is not directly or indirectly referenced by the root object, it can be recycled in the future.
For example, when we buy sunshine rose grapes in a fruit store, if we lift the root of the grape, the edible fresh flesh will be carried along with the lifting action, while the stale flesh will fall off, and the fallen flesh can be recycled as garbage.