How does Garbage Collection in Java work?

后端 未结 9 2140
生来不讨喜
生来不讨喜 2021-02-08 04:36

I was wondering how the garbage collector in Java deals with the following situation.

Object A has a reference to Object B and Object B has a reference to Object C. The

相关标签:
9条回答
  • 2021-02-08 05:15

    As usual, this article is a must-read for whoever wants to understand what garbage collection does. It is well-written and has explanatory drawings.

    0 讨论(0)
  • 2021-02-08 05:17

    I think the logic is different. If the object is not accessible from a thread then it can be collected.

    0 讨论(0)
  • 2021-02-08 05:17

    If there is no reference to object, then it will be suitable for GC to proceed

    0 讨论(0)
  • 2021-02-08 05:23

    B and C are eligable for garbage collection because you can't access them any more. With the unpredicatbility of the garbage collector all we know is they are quite likely to get collected at some point in the future.

    0 讨论(0)
  • 2021-02-08 05:28

    B has no reference to it so it will be garbage collected first, then it will understand that C has no reference to it, so C will be garbage collected. It is for illustration, Jvm is smart enough to scoop them in one sweep.

    0 讨论(0)
  • 2021-02-08 05:31

    Yes, B and C are eligible for garbage collection, if they can't be reached from any GC root (GC roots are usually all Threads and all references on the stack).

    0 讨论(0)
提交回复
热议问题