user3833726
user3833726

Reputation: 23

Java: Will an unreachable object which points to reachable object be garbage collected?

Suppose we have a situation like this:

Object A is unreachable, but it has a reference which points to a valid, reachable object. So will object A be garbage collected? Or we are at risk of memory leak?

EDIT1

Specifically, I wrote a class tri-nary tree, which has:

class Node {
   Node left, mid, right;
   int data;

...
}

I implemented delete(Node p) function, which makes p unreachable by set its parent reference to null. However, the other node in the tree (called m), will call this one before deleting p:

m.mid = p.mid;  
delete(p);    // Make p unreachable

I just want to make sure that that p will be garbage collected, but m still keeps a reference to p.mid

Upvotes: 1

Views: 561

Answers (1)

Stephen C
Stephen C

Reputation: 718986

Object A is unreachable, but it has a reference which points to a valid, reachable object. So will object A be garbage collected?

Yes. (Eventually). An unreachable object is a candidate for garbage collection.

Or we are at risk of memory leak?

No.

When an object is unreachable, any references that it holds are:

  • irrelevant to the computation,
  • irrelevant to its own reachability, and
  • irrelevant to the reachability of the objects that those references refer to.

Now, it may take a long time (i.e. multiple GC runs) before your Object A is actually garbage collected. And until it is actually garbage collected, the closure of objects that it refers too won't be collected either. However, this is not a memory leak. If the JVM needs the memory, you can be assured1 that all unreachable objects are collected before the JVM throws an OOME.


1 - ... modulo certain JVM GC option settings ...

Upvotes: 4

Related Questions