Java: enough free heap to create an object?
<p>I recently came across this in some code - basically someone trying to create a large object, coping when there's not enough heap to create it:</p>

<pre><code>try {
    // try to perform an operation using a huge in-memory array
    byte[] massiveArray = new byte[BIG_NUMBER];
}
catch (OutOfMemoryError oome) {
    // perform the operation in some slower but less
    // memory intensive way...
}
</code></pre>

<p>This doesn't seem right, since Sun themselves recommend that you shouldn't try to catch <code>Error</code> or its subclasses. We discussed it, and another idea that came up was explicitly checking for free heap:</p>

<pre><code>if (Runtime.getRuntime().freeMemory() &gt; SOME_MEMORY) {
    // quick memory-intensive approach
}
else {
    // slower, less demanding approach
}
</code></pre>

<p>Again, this seems unsatisfactory - particularly in that picking a value for <code>SOME_MEMORY</code> is difficult to easily relate to the job in question: for some arbitrary large object, how can I estimate how much memory its instantiation might need?</p>

<p>Is there a better way of doing this? Is it even possible in Java, or is any idea of managing memory below the abstraction level of the language itself? </p>

<p><strong>Edit 1:</strong> in the first example, it might actually be feasible to estimate the amount of memory a <code>byte[]</code> of a given length might occupy, but is there a more generic way that extends to arbitrary large objects?</p>

<p><strong>Edit 2:</strong> as @erickson points out, there are ways to estimate the size of an object once it's created, but (ignoring a statistical approach based on previous object sizes) is there a way of doing so for yet-uncreated objects?</p>

<p>There also seems to be some debate as to whether it's reasonable to catch <code>OutOfMemoryError</code> - anyone know anything conclusive?</p>
