Java how to determine whether an object is alive

1. Reference counting

引用计数器法:每个对象设置一个引用计数器,当对象被引用,计算器加1,当引用失效,计算器减一。当计数器为0时,
表示引用失效,也就是"死对象",可以被垃圾回收机制回收。
缺陷:无法解决循环依赖的问题。有两个对象A、B。当A引用B,B引用A时,那么此时A、B对象都不为0,垃圾回收机
制无法被回收。

2. reachability algorithm (reference chain method)

从GCRoot开始向下搜索,如果一个对象没有与任何引用链相连时,表示这个对象是垃圾对象,
可以被垃圾回收机制回收。
GC Roots的对象:
虚拟机栈中的引用对象
方法区类静态引用对象
方法区常量池引用对象
本地方法栈JNI引用的对象

Note: Although the algorithm can determine whether an object is garbage object, but the object is not garbage can be recycled. When an object is unreachable GC Root, the object will not immediately be recovered, but a reprieve for the stage, to the recovery of the real need to go through two marks. If the object is not referenced in reachability analysis with GC Root of the chain, then the time will be the first mark and conduct a screening, screening condition is whether it is necessary to perform the finalize () method. When the object does not cover the finalize () method has been called or virtual machine, then that is not necessary.
If the object is necessary to perform a finalize () method, then the object will be placed in a called F-Queue to queue, the virtual trigger a Finalize () thread to execute, this thread is a low priority, and virtual machine will not promise has been waiting for it to run to completion, it is as if finalize () or slow implementation of a deadlock occurs, it will result in F-queue queue have been waiting for, resulting in a collapse of the memory recovery system. GC F-Queue object is in a second labeled, then, the object will be removed "will recover" set wait recovered.

Conditions trigger garbage collection

Under normal circumstances will not be implemented only when the virtual machine is idle or the current lack of heap memory, will trigger the execution, sweep surfaces that are not referenced by any object, and add them to the collection to recycling, recycling .

Published 77 original articles · won praise 39 · views 80000 +

Guess you like

Origin blog.csdn.net/qq_33824312/article/details/105125735