Running the code below on Windows 10 / OpenJDK 11.0.4_x64 produces as output used: 197
and expected usage: 200
. This means that 200 byte arrays of one million elements take up approx. 200MB RAM. Everything fine.
When I change the byte array allocation in the code from new byte[1000000]
to new byte[1048576]
(that is, to 1024*1024 elements), it produces as output used: 417
and expected usage: 200
. What the heck?
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<byte[]> data = new ArrayList<>();
for (int n = 0; n < 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();
}
}
Looking a bit deeper with visualvm, I see in the first case everything as expected:
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:
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.)
Any ideas what is happening here?