0

"Orphaned cycles" may not be exactly the correct term for what I'm trying to describe. Here is an example of what I'm trying to describe in code:

public class Container {
    private Container 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();
        Container c2 = new Container();
        c1.setContainer(c2);
        c2.setContainer(c1);
        //c1 and c2 now each hold a reference to each other,
        //will they be garbage-collected once this method falls out of scope?
    }
}

Given a graph of references in memory containing a cycle, can the JVM garbage collect the memory references once the cycle is unreachable by code? Or is this a memory leak?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
rybosome
  • 5,046
  • 7
  • 44
  • 64

1 Answers1

1

While this theoretically depends on the JVM implementation (the JVM isn't actually required to implement garbage collection at all, and some very small embedded ones don't), all modern JVMs use a variation of mark-and-sweep, which starts at your main method and goes through to find (mark) everything that's reachable and throws (sweeps) away everything else. Circular data structures that aren't reachable from the main program will get collected.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152