Reputation: 2330
I have a theoretical question I can't find an answer to -
Assuming I have a singelton instance A with inner private member a and a public
setter, now let's assume I set this member from another instance of
class type B in a private method as a consequence to some event
i.e. if something happen I will call A.setA(a) from B's private method.
My question is -
Once the use in instance of class B is over and the instance of class A still "lives" in the system,
will the instance of class B get garbage collected?
That is if B use anonymous member to init A's a.
Thanks in advance.
Edit - Code example -
public class A {
Object a;
public void setA(Object a) {
this.a = a;
}
}
public class B {
private void foo() {
if(...condition) {
A.getInstance().setA(new Object());
}
}
}
To further explain - the instance of class A is a singleton in the system, there is no other class referencing to the instance of class B and it's done it's part after setting A's private member
Upvotes: 1
Views: 94
Reputation: 140457
Any object becomes eligible to be collected as garbage as soon as it is no longer considered alive.
An object is alive when there is a reference to it from another life object. In other words: as long as that B object is referenced from somewhere, it can't be collected. See here for example.
It absolutely does not matter here what code within the B class is doing. The only thing that matters is: is the B object still referenced from somewhere. In that sense you should rather study how GC works in general, see here for example.
Upvotes: 1
Reputation: 1959
It's clear from the basics of the GC standards: the garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.
If there are private class attribute istantiated by a superclass, that will live as long as any of its relationship with used objects.
You can easily keep track of this implementing your own scenario and keep it monitored via jdk instruments suck as Java Mission Control
Upvotes: 0