Sunday, 15 September 2013

Will the JVM detect orphaned cycles?

Will the JVM detect orphaned cycles?

"Orphaned cycles" may not be exactly the correct term for what I'm trying
to describe; I heard it from a co-worker, but it may have just been a
casual term. Here is an example of what I'm trying to describe in code:
public class Container {
private Container otherContainer;
public Container(Container otherContainer) {
this.otherContainer = otherContainer;
}
public void setContainer(Container otherContainer) {
this.otherContainer = otherContainer;
}
}
public class Main {
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
Container c1 = new Container(null);
Container c2 = new Container(c1);
c1.setContainer(c2);
// c1 and c2 now each hold a reference to each other; can they be
garbage-collected
// once this method exits?
}
}
Essentially, the question boils down to this - given a graph of references
containing a cycle, can the JVM collect the references once it would be
safe to do so, or is this a memory leak?

No comments:

Post a Comment