I have this code
int[] i = new int[127*1024];
is working
int[] i = new int[128*1024];
is throwing
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at memory.main(memory.java:123)
running this using the following command in a 64 bit windows machine, jdk 1.8
java -Xms1M -Xmx1M memory
As per my understanding, java int is of 4 bytes(32 bit) and int[] array is an object. In the above case its failing if the size is 131.072 bytes(128 * 1024) with 1mb of heap space Can anyone help in explaining why its going out of memory?
-
2I'm sorry, did you assume nothing else in the heap was taking up any space? Say, all the other infrastructure for a Java VM?Louis Wasserman– Louis Wasserman2017年10月18日 23:09:45 +00:00Commented Oct 18, 2017 at 23:09
-
2And the size is 128*1024*4 bytes (+a few bytes of overhead), so 4 times as much as you said.biziclop– biziclop2017年10月18日 23:17:31 +00:00Commented Oct 18, 2017 at 23:17
-
1You're using at least 128*1024*4=524288 bytes for this array, leaving less than 1/2Mb for the rest of Java. Never seen it run that small in 20 years.user207421– user2074212017年10月18日 23:21:22 +00:00Commented Oct 18, 2017 at 23:21
-
this counts to 4 * 128 * 1024 ~512 bytes... u mean additional bytes overhead also accounts to 512 bytes to fill 1 mb?Vinod Krishnan– Vinod Krishnan2017年10月18日 23:40:30 +00:00Commented Oct 18, 2017 at 23:40
1 Answer 1
Space for every element of the array is allocated on array creation.
All elements are initialized to 0
.
int
values are 4
bytes, so this array causes 128 * 1024 * 4
bytes to be allocated, which is 0.5 Mb.
Your array is not the only object on the heap at that line of code, which is why your JVM explodes, even though you gave it 1 Mb of memory.
You need to give more memory to your JVM to avoid this error.