An int array of 100 million ints should be 400 MB, right?
One int = 4 bytes
So if I set the VM to have a max heap of 1024m with -Xmx1024m why does this code fail:
public static void main(String[] args) {
int[] b = new int[100000000]; //100 mil = 400mb
System.out.println("ok");
int[] c = new int[100000000];
}
This is the output:
ok
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Main.main(Main.java:9)
Solution – break it up!
public static void main(String[] args) {
int[] a = new int[50000000]; //50 mil = 200mb
System.out.println("ok 1");
int[] b = new int[50000000];
System.out.println("ok 2");
int[] c = new int[50000000];
System.out.println("ok 3");
int[] d = new int[50000000];
System.out.println("ok 4");
}
The problem lies in the fact that when you’re creating this int[], it requires contiguous memory of 400mb. Basically this means, you need a solid block of 400mb of memory for use. Due to fragmentation of the heap, it can’t find a solid 400mb block of memory to use. That’s why you’re getting the out of memory error in this situation.