Reputation: 59
I was wondering if the following code produced some sort of memory leak in Java. Anyways here's the code:
public class test {
public static void main(String[] args){
A a = new A();
a.x = new A(new A(new A(new A(a))));
a.x.x = null;
}
}
class A{
public A x = null;
A() {}
A(A a){
x = a;
}
}
Upvotes: 0
Views: 157
Reputation: 718788
There is no memory leak in that code.
When the a
variable in main
goes out of scope, all objects will be unreachable and eligible to be garbage collected.
I was wondering if setting
a.x.x
tonull
loses the reference to the otherx
's withina.x
's multiplex
's if that makes any sense...
Not a lot :-)
Proper memory management in Java does not depend on things not losing references to other things ... or not. The overarching rule is that if an object can no longer be reached by any executing code, it cannot influence the computation, and it is eligible to be garbage collected. The GC will deal with an unreachable object as, and when this is necessary ... but generally at the time of its choosing.
Memory leaks in Java actually occur because an object is reachable when you don't want them to be; e.g. when you "hang onto" objects by keeping links to them in a static
collection.
Upvotes: 0
Reputation: 159096
If you number the A's:
A a = new A();
// 1
a.x = new A(new A(new A(new A(a))));
// 2 3 4 5
Then you have a circular chain:
a → 1 → 2 → 3 → 4 → 5 → 1
When you break the circle using a.x.x = null
, you get:
a → 1 → 2
Instances 3, 4, and 5 are now eligible for garbage collection.
Then, when main
exits, a
goes out of scope, and instances 1 and 2 are also eligible for garbage collection.
Note that program will likely end before GC has a chance to do anything.
Upvotes: 5