title: Java optimization to prevent heapspace out of memory
body: <p>Ok, I have a problem in a particular situation that my program get the out of memory error from heap space.</p>
  
  <p>Let's assume we have two ArrayList, the first one contains many <code>T</code> objects, the second one contains <code>W</code> object that are created from the <code>T</code> objects of first List.</p>
  
  <p>And we cycle through it in this way (after the cycle the list :</p>
  
  <pre><code>public void funct(ArrayList&lt;T&gt; list)
  {
    ArrayList&lt;W&gt; list2 = new ArrayList&lt;W&gt;();
    for (int i = 0 ; i &lt; list.size() ; i++)
    {
       W temp = new W();
       temp.set(list.get(i));
       temp.saveToDB();
       list2.add(temp);          
    }
  
    // more code! from this point on the `list` is useless
  }
  </code></pre>
  
  <p>My code is pretty similar to this one, but when <code>list</code> contains tons of objects I often get the heap space out of memory (during the for cycle), I'd like to solve this problem.</p>
  
  <p>I do not know very well how the <code>GC</code> works in java, but surely in the previous example there are a lot of possible optimization.
  Since the <code>list</code> is not used anymore after the for cycle I thought as first optimization to change from <code>for loop</code> to <code>do loop</code> and empty the <code>list</code> as we cycle through it:</p>
  
  <pre><code>public void funct(ArrayList&lt;T&gt; list)
  {
    ArrayList&lt;W&gt; list2 = new ArrayList&lt;W&gt;();
    while (list.size() &gt; 0)
    {
       W temp = new W();
       temp.set(list.remove(0));
       temp.saveToDB();
       list2.add(temp);
    }
  
    // more code! from this point on the `list` is useless
  }
  </code></pre>
  
  <p>Is this modification useful?
  How can I do a better optimization to the above code? and how can I prevent heap space out of memory error? (increasing the <code>XMX</code> and <code>XMS</code> value is not a possibility).</p>