“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

preface

Reference counting has its advantages and disadvantages as the original garbage collector algorithm, and although reference counting is no longer used by modern JVMS for garbage collection, it is not obsolete.

Reference counting algorithm

The core point of reference counting algorithm is to maintain the reference number of the current object by setting the reference calculator, so as to determine whether the current reference number is 0, to determine whether the garbage object, if the case is 0, start GC for garbage collection

Here we refer to: reference counters; Of course, there is nothing to become, nothing to lose; Because of this reference, the reference counting algorithm is somewhat different from other GC algorithms.

So when does the quoted value change?

When the reference relationship of an object changes, the reference counter automatically changes some values.

[Q] What is a change in reference relationship?

[A] Very simple, just like A reference space, after being referenced by one object A, the number of references is increased by one, after being referenced by the second object B, the number of references is increased by one again. If A is not referenced at this time, the number of references is decreased by one. Once the reference number is 0, the recycling action will be carried out immediately

With that said, let’s use the code for some simple examples.

example

function fn() {
  const num1 = 1
  const num2 = 2
}

fn()
Copy the code

In this code, num1 and num2 are no longer accessible after the fn method is executed, because their reference count === 0 is reclaimed

Simple summary

The reference counting algorithm maintains a reference count value for each object to count how many objects it is used by

  • Every time a new reference points to the object, the reference counter is +1
  • This counter is -1 whenever a reference to the object is invalid

When the number of references is zero, it indicates that the object is not referred to by any reference and can be considered garbage, so the GC algorithm is immediately executed to collect garbage