I want to get the exact amount of memory which is needed to create the biggest possible array in Java.
My Test Program:
public class MemoryOfArraysTest {
public static void main(String... args) {
Object[] array = new Object[Integer.MAX_VALUE - 2];
}
}
I know from own testing that the maximum length of an array is Integer.MAX_VALUE - 2
(2147483645).
If the number is greater you will get following error:
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at MemoryOfArraysTest.main(MemoryOfArraysTest.java:3)
But this is only one step getting closer to the maximum length of an array. The other problem is the memory your VM can use. You can specify the memory with -Xmx.
If I run my class with with java -Xmx1g MemoryOfArraysTest
(only 1GB of memory) I get expected error:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at MemoryOfArraysTest.main(MemoryOfArraysTest.java:3)
If I run it with java -Xmx10g MemoryOfArraysTest
(10GB of memory) it just works.
This is what I have so far. But what is the exact amount of memory my program needs? Preferably in KB´s. Is there maybe a way to calculate it?