title: Java: Clear memory between independent runs
body: <p>I implemented a heuristic in Java that solves an optimization problem for a given input. The heuristic can run for thousands of iterations and create lots of objects of varying complexity.</p>
  
  <p>In order to test it, I have thousands of test inputs. My main method takes all inputs and sequentially starts the heuristic for each input in a loop. The results are stored in a separate file for each input.</p>
  
  <p>When I run the program, it always stops after producing 218 or 219 and throws an "OutOfMemoryError". Once it says <code>Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded</code> and once <code>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space</code>.</p>
  
  <p>My guess is, the program creates too many objects over time until it runs out of memory when computing the 218th or 219th input. Every instance is computed in an independent run. Hence, it should solve the problem to clear the memory and getting rid of all created objects after the result for an input is stored and before the next input is parsed. Is that correct? I heard using <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#gc%28%29" rel="nofollow">System.gc()</a> is bad practice, but what else would you recommend in my case?</p>
  
  <p><strong>Edit</strong>:
  To specify what I want: Instead of pressing "start" for each input, I implemented the loop to do that for me. However, it seems like it doesn't behave the same way and it keeps old objects from previous runs. Can I change my java code in such a way that it behaves similar to starting the program anew for each input? Or do I have to use a shell skript that starts my heuristic for each input separatly to make it work?
  I have never used any JVM parameters and it seems to me like they don't really tackle the problem.</p>
  
  <p><em>Resolved</em>: There was in fact a memory leak that I discovered and fixed. No System.gc() needed. Thanks for helping anyways!</p>