title: Why doesn't the Java garbage collector collect garbage?
body: <p>I'm playing with a horrifying data structure which basically is a tree, and each node stores references to its children in a <code>HashMap</code> object. I'm having troubles freeing memory whenever I need to get rid of the root and all its subtrees except one, by setting this latter subtree as the new root. I thought it might be some bug in my data structure, maybe some reference that I forgot to be there, so nothing becomes eligible for garbage collection. But I wanted to try something much simpler first, and implemented the following test:</p>
  
  <pre><code>import java.io.BufferedReader;
  import java.io.InputStreamReader;
  import java.io.IOException;
  
  public class MyNode {
          MyNode next;
          int somedata;
  
          public MyNode(MyNode n) {
              next = n;
              somedata = 0;
          }
  
          public static void main(String[] args) throws IOException {
              MyNode p = new MyNode(null);
              BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              for (int i=0; i&lt;10000000; i++) {
                  MyNode n = new MyNode(p);
                  p = n;
              }
              while (p!=null) {
                  MyNode p1 = p.next;
                  p.next = null;
                  p = p1;
              }
              in.readLine();
          }
  }
  </code></pre>
  
  <p>When main reaches <code>in.readline()</code>, I can see in htop that the process still has 250MB or so allocated for itself, and nothing gets freed. I obviously first tried to simply do</p>
  
  <pre><code>p = null;
  </code></pre>
  
  <p>instead of the while loop. But it didn't work so I came up with the previous code.</p>