Reputation: 189
My maths says the following Java program would need approx 8GB (2147483645 * 4 bytes) of RAM:
package foo;
public class Foo {
public static void main(String[] args) throws Exception {
int[] arr = new int[Integer.MAX_VALUE-2];
Thread.sleep(500000L);
}
}
This is backed up by observing the program when running:
But unless you set the max heap to around 12.5GB, the program fails to start:
$ java -Xmx12000m -cp ./ foo.Foo
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at foo.Foo.main(Foo.java:5)
$ java -Xmx12500m -cp ./ foo.Foo
//this works
Can understand the need for a bit of wiggle-room but why do we need so much?
Upvotes: 5
Views: 352
Reputation: 384
Its because of the MinHeapFreeRatio default value (which is 40%). If you want to "need" less then you have to specify it: e.g. 5%
-XX:MinHeapFreeRatio=5
Also, you need to change memory allocated to the young generation as it plays a important role in memory allocation:
After total available memory, the second most influential factor affecting garbage collection performance is the proportion of the heap dedicated to the young generation.
try this:
java -Xmx9g -XX:MinHeapFreeRatio=1 -XX:MaxNewSize=256m -cp ./ foo.Foo
https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/sizing.html
Upvotes: 5