I've written the following test to check maximum available heap memory:
import java.util.*;
public class Memory {
public static void main(String[] args) {
long maxMB = Runtime.getRuntime().maxMemory() / 1048576L;
System.out.println("Maximum memory is " + maxMB + " MB.");
ArrayList<byte[]> allocated = new ArrayList<>();
try {
while (true)
allocated.add(new byte[1024*1024]);
} catch (OutOfMemoryError e) {
System.out.println("allocated " + allocated.size() + " MB before running out of memory.");
}
}
}
However, when I test this, it appears that only half of the "available" memory can actually be allocated:
$ java -Xmx512m Memory
Maximum memory is 512 MB.
allocated 255 MB before running out of memory.
$ java -Xmx1024m Memory
Maximum memory is 1024 MB.
allocated 511 MB before running out of memory.
Anyone know why this would be the case?