How to prevent OutOfMemoryError by checking heap status
<p>I thought checking <code>Runtime.getRuntime().freeMemory()</code> would do it, but the following test appears to show it is not useful:</p>

<pre><code>List&lt;Byte&gt; listDebug = new ArrayList&lt;Byte&gt;();
Log.d("Free memory", String.format("%1$.2f", (float)Runtime.getRuntime().freeMemory()/(1024*1024)));
for (int i = 0; i &lt; 100; i++) {
    try {
        listDebug.addAll(Arrays.asList(new Byte[1024 * 100]));
        Log.d("Free memory", i + ":" + String.format("%1$.2f", (float)Runtime.getRuntime().freeMemory()/(1024*1024)));
    } catch (Exception ex) {
        Log.d("Free memory", ex.getMessage());
    }
    catch (Error e)
    {
        Log.d("Free memory", e.getMessage());
    }
}
</code></pre>

<p>The output is the following:</p>

<pre><code>03-09 03:16:11.267: D/Free memory(3860): 1.30
03-09 03:16:11.277: D/Free memory(3860): 0:1.25
03-09 03:16:11.287: D/Free memory(3860): 1:2.63
03-09 03:16:11.298: D/Free memory(3860): 2:3.86
03-09 03:16:11.298: D/Free memory(3860): 3:3.08
03-09 03:16:11.317: D/Free memory(3860): 4:4.85
03-09 03:16:11.317: D/Free memory(3860): 5:4.06
03-09 03:16:11.317: D/Free memory(3860): 6:3.28
03-09 03:16:11.367: D/Free memory(3860): 7:7.84
03-09 03:16:11.367: D/Free memory(3860): 8:7.06
03-09 03:16:11.367: D/Free memory(3860): 9:6.27
03-09 03:16:11.387: D/Free memory(3860): 10:7.84
</code></pre>

<p>The testing app crashes after expanding the list 11 times when <code>freeMemory()</code> returns the highest number.  I am deeply puzzled. Is my testing code fundamentally flawed or <code>freeMemory()</code> is completely irrelevant to <code>java.lang.OutOfMemoryError</code>?</p>
