This is the 20th day of my participation in the August More Text Challenge

This paper continues the previous article | the JVM garbage collection strategy (a), go ahead with the JVM object recovery strategy.

Object recycling strategy

3.1 Reference counting method

Determines whether an object is referenced by its reference counter. For example, for an object of ObjectA, if ObjectB references it, the reference counter of ObjectA is increased by 1. When ObjectB no longer references the object, the reference counter of ObjectA is decreased by 1.

If ObjectA’s reference counter turns to 0, then no object is referring to it, triggering the reclaim mechanism. The following figure shows the normal reference counting process.

It is efficient to use reference counting to determine whether an object needs to be recycled, but there is an extreme case where there is a circular reference between objects, i.e. ObjectA refers to ObjectB, ObjectB refers to ObjectC, and ObjectC refers to ObjectA, as shown in the figure below. Reference counting doesn’t help. How could this be, some ask? Let’s assume that there is an object O4 that once referred to O1, but O4 cancels its reference to O1. O1, O2, and O3 should all be garbage collected. Because they reference each other repeatedly, their reference count cannot reach 0, that is, they cannot be collected.

It is important to note that Java does not use reference counting to determine whether an object needs to be reclaimed, it uses reacablity analysis.

3.2 Accessibility analysis

The solution of reachability analysis is to search down with GC Roots as the starting point, and the path is called the Reference Chain. If an object has no path linked to the root object, the object is judged unreachable and can be reclaimed.

As shown in the figure, Object [1-5] has a path linked to the root Object, so it cannot be reclaimed. Object [6-9] has no path linked to the root Object, so it can be recycled.

GC Roots contains objects

  • The object referenced by the constant in the method area

  • The object referenced by the class static property in the method area

  • Objects referenced by JNI (or Native methods) in the Native method stack

  • Objects referenced in the virtual machine stack are generally local variables in our methods.


Didn’t see enough, please jump to the next article JVM | garbage collection strategy (3)