0

Let's say there are following four objects in a Java program:

  • main
  • a
  • b
  • c

The dependencies are as follows:

main ==> a ==> b ==> c

In other words, main uses a, a uses b, b uses c.

Now, value of object a changes from reference to b to null. What it means is that there are no active references to b, making it available for garbage collection:

main ==> a =/=> b ==> c

What could happen now:

A) In laymans terms, b can be garbage collected at any time. My assumption is that c will become elligible for gargabe collection only after b is garbage collected.

B) However, I imagine this could be a case that JVM could somehow distinguish between references to c from GC-eligible and non-GC-eligible objects, and therefore mark c as eligible at the same time as b.

Is the behaviour determined by Java Language Specification, or any JVM-related specification? Or is it left for the JVM implementation to decide?

automatictester
  • 2,436
  • 1
  • 19
  • 34
  • 1
    Some related questions: https://stackoverflow.com/questions/31451346/how-garbage-collector-works-under-the-hood-to-collect-dead-object, https://stackoverflow.com/questions/8812635/how-does-garbage-collector-identify-roots?rq=1, and https://stackoverflow.com/questions/10587868/java-how-can-garbage-collector-quickly-know-which-objects-do-not-have-referenc?rq=1 – Slaw Nov 12 '18 at 13:23
  • 1
    All that a garbage collector cares for, is that `main` and `a` are still reachable. Everything else is garbage. Despite its misleading name, a garbage collector never looks at the garbage. – Holger Nov 12 '18 at 16:03

1 Answers1

0

Thanks to this link, I believe option B is correct: https://www.dynatrace.com/resources/ebooks/javabook/how-garbage-collection-works/ Once b and c are no longer reachable from GC roots, they are both collectible at the same time.

automatictester
  • 2,436
  • 1
  • 19
  • 34