Why does OutOfMemoryError occur for -Xmx12m but not -Xmx13m?

How come, if I executed the following class with: java -Xmx12m OOM , it is not with the message java.lang.OutOfMemoryError Java heap space . But if it works with java -Xmx13m OOM .

 class OOM { static final int SIZE=2*1024*1024; public static void main(String[] a) { int[] i = new int[SIZE]; } } 

I thought that int is 4 bytes, so 2 * 1024 * 1024 * 4 = 8 388 608 bytes. He's still below 12, right? So, how did -Xmx12m , but -Xmx13m work?

+5
source share
2 answers

The -Xmx sets the total (maximum) heap size. However, a Java heap usually consists of 2 (or more) spaces 1 and the Java object must fit into one space.

When you set the heap to 12mb, none of the spaces is large enough 2 to hold a single ~ 8mb object. When you increase the total heap size to 13 mb, one of the spaces is large enough.


1 - "new" or "eden" space, where usually new objects stand out. An "old" or "permanent" space is the place where objects end after they have survived a certain number of GC cycles. However, really large objects (for example, yours) can be allocated directly to the "old" space. (Note: this is a simplification ...)

2 - You can change the relative size of the new space, but this has other consequences. For example, if you reduce the size of the new space too much, you are likely to increase the percentage of “full” GC ..., which affects both throughput and GC pauses.

+4
source

I agree with Stefan S.

I would like to provide more information from this blog from Alexey Zhebel

The diagram below details the architecture of Java memory.

Heap memory (-Xmx) = Youn gen (Eden space) + space for survival + Olde gen (shadow space)

It seems that your total heap memory crosses 12 m but does not exceed 13 m.

enter image description here

+2
source

All Articles