I'm trying to create an integer-array with 1 billion (1 000 000 000
) elements, like this:
int[] prime_table = new int[1000000000];
but the VM runs out of Heap-memory on the line above:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at algorithms.Algorithm.run(Algorithm.java:34)
at Main.main(Main.java:18)
So I investigated a bit: in Java, an Integer is 32bit, so that means I'm allocating a 32 000 000 000
bit field, which is roughly 3 814.69727
megabytes. I launched the VM with enough heap:
java -Xms4g -Xmx4g Main
and this tells me, the VM is getting 3926MB of heap-size (just before allocating the array):
System.out.println( Runtime.getRuntime().totalMemory() / (1024*1024) +"MB");
That seems fine, so why is it throwing the error?