javagarbage-collection

How does Java handle weak reference with cycle?


Suppose I have objects A and B which strong/regular reference each others, forming a reference cycle. The path from A to the GC root is dominated by a weak reference (represented by the dashed arrow in the image below). In this case, what is the reachability of object A?

Specifically, if I call java.lang.ref.Cleaner.register(A, cleanup_action), is cleanup_action going to run? (the document specifies that only happens when A is phantom reachable)

illustration of the reference graph


Solution

  • How does Java handle weak reference with cycle?

    Correctly. And consistently with the way that the GC handles cycles in general.

    I am assuming that you are not asking about how the JVM / GC implements Reference classes and their special behavior. But even at that level, cycles involving Reference objects are dealt with the same way as cycles that don't involve Reference objects.

    In your example, you registered A with the cleaner, so A will be "cleaned", and the existence of the cycle involving another phantom reachable object (B) doesn't change that.

    In this case, what is the reachability of object A?

    It is weakly reachable ... unless A or B are strongly reachable via references that you haven't shown.

    Specifically, if I call java.lang.ref.Cleaner.register(A, cleanup_action) is cleanup_action going to run?

    The cleanup action registered with the cleaner should happen after the weak reference has been broken and the GC detects that A is now only phantom reachable. That will probably be after a GC run after the weak reference has been broken.

    You can view the phantom reference that is created when you register an object with a cleaner as being "internal" to the cleaner. Either way, the cleaner doesn't do its thing until the object is phantom reachable; i.e. it is no longer strongly, softly or weakly reachable. And ... of course ... the cleaner only knows about the PhantomReference objects that it created itself.


    The path from A to the GC root is dominated by a weak reference ...

    Actually, reachability paths start at a GC root. I don't think this is at root of your uncertainty, but it is a good idea to use the terminology correctly. It makes it easier for other people to understand what you are trying to saying.