Java recycling mechanism and recycling algorithm

harm! Why write this article? Today, Ali asked about the Java recycling mechanism in a telephone interview for Java technical internship. I clearly learned about it in the video, but I didn't think of it at the time. I was extremely embarrassed and wrote an article to deepen my impression!

Java's memory recovery is different from C++. C++ does not have an automatic recovery mechanism. The requested space needs to be released manually. Unlike Java, it has a garbage collection mechanism. When a programmer writes a program, if he does not want to use an object, he only needs to assign a value. If it is null, the Java memory recycling mechanism will release the space requested by the useless object.

The Java garbage collection mechanism relies on the garbage collection algorithm to find useless objects. No matter which garbage collection algorithm, there are two steps:

  1. Useless object found
  2. Reclaim space occupied by useless objects

With my superficial knowledge, I temporarily understand two garbage collection algorithms:

  1. Reference counting
  2. Root search algorithm (reference reachability method)

Next, let's talk about the specific content of the algorithm in detail:

1. Reference counting method:

  Each object in the heap has a reference count. Every time it is referenced, the count is increased by one, the value of the referenced variable is set to null, and the reference value is reduced by one. When the reference count is zero, the object becomes a useless object.

  Advantages: Simple
  Disadvantages: Useless objects referenced circularly cannot be identified

2. Root search algorithm

  The reference relationship is regarded as a graph by the program, starting from GC ROOT and searching downwards to form a reference chain. A series of GC ROOT forms a series of reference chains. If an object is unreachable to these reference chains, it is considered useless. .

  The objects that can be regarded as GC ROOT are:
    (1) Objects referenced in the virtual machine stack
    (2) Objects referenced by class static properties in the
    method area (3) Objects referenced by constants in the method area
    (4) References in the Java local interface Object

Feeling! Alas~ There is no end to learning, I have just started...

Guess you like

Origin blog.csdn.net/L333333333/article/details/104616985