当前位置:网站首页>How GC determines whether an object can be recycled

How GC determines whether an object can be recycled

2022-06-25 15:30:00 ITenderL

GC How to judge whether an object can be recycled

  • Reference counting : Each object has a reference counter , When adding a reference, the counter is incremented 1, Counter decrement on reference release 1, When count is 0 when , Recyclable .
  • Reachability algorithm : from GC Roots Start looking down , The search path is the reference chain . When an object arrives GC Roots When there is no reference chain , Then prove that this object is not available , Then the virtual opportunity judgment is a recyclable object .

Reference counting , There may be A Refer to the B,B Also cited A, Even if they don't use it anymore , But because of mutual reference Counter =1 Can never be recycled .

It can be used as GC Roots There are :

  1. Virtual machine stack ( Table of local variables in stack frame ) Object referenced in
  2. Object referenced by static property of method area
  3. Objects referenced by static constants in the method area
  4. Local method stack JNI(Native Method ) Referenced object

Unreachable objects are not recycled immediately
The unreachable objects in the reachability algorithm do not die immediately , The object has a chance to save himself . It takes at least two marking processes for an object to be declared dead by the system : For the first time, accessibility analysis found that there was no relationship between GC Roots Linked reference chain , The second one was created automatically by the virtual machine Finalizer Queue to determine whether it needs to be executed finalize() Method .
When the object becomes (GC Roots) Unreachable time ,GC It will determine whether the object covers finalize Method , If not covered , Then recycle it directly . otherwise , If the object has not been executed finalize Method , Put it in the F-Queue queue , The... Of the objects in the queue is executed by a low priority thread finalize Method . perform finalize After the method ,GC Whether the object is reachable will be judged again , If you can't reach , Then recycle , otherwise , object “ resurrection ” Each object can only be triggered once finalize() The method is due to finalize() Methods are expensive to run , High uncertainty , The order in which the individual objects are invoked cannot be guaranteed , It's not recommended , Suggest forgetting it .

原网站

版权声明
本文为[ITenderL]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200502168416.html