Reputation: 294
Let me explain it the following way: you have an Object a holding a reference to an Object b. you know that if only a holds a reference to b, then b is not needed anymore, and should be collected by the GC.
Now imagine, a is always accessible.
The gc realizes that b can be accessed through a.
Therefore, the GC will never collect b!
How can i make the GC collect b if only a has a reference to it?
is there any way to make a reference that is ignored by the GC (weak reference), so that when the above conditions are met, the gc collects b, leaving a null pointer to a?
Upvotes: 2
Views: 100
Reputation: 13682
You used the tag "weak-references" in your question, and that's the answer right there. Java has a WeakReference
class for doing just this, holding references to objects that can nevertheless still be garbage collected. If the object to which you have a WeakReference
gets collected, the WeakReference
returns null.
Upvotes: 3