Java byte array of 1 MB or more takes up twice the RAM : <p>Running the code below on Windows 10 / OpenJDK 11.0.4_x64 produces as output <code>used: 197</code> and <code>expected usage: 200</code>. This means that 200 byte arrays of one million elements take up approx. 200MB RAM. Everything fine.</p>

<p>When I change the byte array allocation in the code from <code>new byte[1000000]</code> to <code>new byte[1048576]</code> (that is, to 1024*1024 elements), it produces as output <code>used: 417</code> and <code>expected usage: 200</code>. What the heck?</p>

<pre><code>import java.io.IOException;
import java.util.ArrayList;

public class Mem {
    private static Runtime rt = Runtime.getRuntime();
    private static long free() { return rt.maxMemory() - rt.totalMemory() + rt.freeMemory(); }
    public static void main(String[] args) throws InterruptedException, IOException {
        int blocks = 200;
        long initiallyFree = free();
        System.out.println("initially free: " + initiallyFree / 1000000);
        ArrayList&lt;byte[]&gt; data = new ArrayList&lt;&gt;();
        for (int n = 0; n &lt; blocks; n++) { data.add(new byte[1000000]); }
        System.gc();
        Thread.sleep(2000);
        long remainingFree = free();
        System.out.println("remaining free: " + remainingFree / 1000000);
        System.out.println("used: " + (initiallyFree - remainingFree) / 1000000);
        System.out.println("expected usage: " + blocks);
        System.in.read();
    }
}
</code></pre>

<p>Looking a bit deeper with visualvm, I see in the first case everything as expected:</p>

<p><a href="https://i.stack.imgur.com/Z7lPo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z7lPo.png" alt="byte arrays take up 200mb"></a></p>

<p>In the second case, in addition to the byte arrays, I see the same number of int arrays taking up the same amount of RAM as the byte arrays:</p>

<p><a href="https://i.stack.imgur.com/W0TnR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W0TnR.png" alt="int arrays take up additional 200mb"></a></p>

<p>These int arrays, by the way, do not show that they are referenced, but I can't garbage collect them... (The byte arrays show just fine where they are referenced.)</p>

<p>Any ideas what is happening here?</p>
