Reputation: 254
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?
Upvotes: 2
Views: 204
Reputation: 120848
Each Object has two headers, with XX:+UseCompressedOops
(which is on by default), the two headers will have 12 bytes
. Plus 4 bytes
to keep the length of the array. Plus some eventual padding that you need to take into account also.
You can use JOL to find out how big it is. An experiment like this:
Object[] array = new Object[100];
for(int i=0;i<100;++i){
array[i] = new Object();
}
System.out.println(GraphLayout.parseInstance(array).totalSize());
shows that it has 1600 bytes
. If I change that size to 1000
, I will get 16000 bytes
.
But that math, you can say that the size of Object[2147483646]
is going to be around 34 GB
.
Notice that there is a big difference between populating that array and not. If it is not populated:
Object[] array = new Object[Integer.MAX_VALUE - 2];
System.out.println(ClassLayout.parseInstance(array).instanceSize());
It will weight arund 8GB
Upvotes: 1