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;
}
}
2 Answers 2
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.
1 Comment
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.xtonullloses 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.
a.x. If you do want to keep it, then it's fine. Also there's no leak becauseagoes out of scope at the end of the method, and therefore ALL objects you created are eligible for collection, but I don't think that's what you wanted to ask about.