Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.OutOfMemoryError: Java heap space while initialising an array

I am trying to initialise an array of boolean type whose size is a 10 digit integer. It keeps on throwing OutOfMemoryException. I have increased the size of the heap space of eclipse to 1024 from 256. Is there anything that I am missing to do?

int size = 1000000000;
boolean[] primesList = new boolean[size];
like image 475
h-rai Avatar asked Oct 11 '13 08:10

h-rai


People also ask

What causes Java Lang OutOfMemoryError Java heap space?

OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java. lang. OutOfMemoryError .


1 Answers

Use java.util.BitSet, which will pack the bits in one-eighth of the space compared to using a boolean array.

The reason boolean array elements take 1 byte instead of 1 bit is because (most) CPU architectures don't provide the ability to directly read and write individual bits of memory. The smallest unit PCs can manipulate has 8 bits. The JVM could pack the bits together, then to modify a bit it would read the byte, modify it, and write it back, but that does not work if multiple threads are modifying the array simultaneously.

As to your original array, it's 1 billion booleans, one byte each, which is 1 billion bytes or ~954 MB. So a 1024 MB heap ought to be enough (?). Perhaps it can't find a contiguous chunk of memory big enough, or perhaps you have not set the memory parameter correctly. Print the value of Runtime.getRuntime().maxMemory() to find out the maximum heap size that Java is using. For 1024 MB the parameter should be -Xmx1024M.

Final note: As of Java 7 you can use underscores in numbers to make them more readable. So you can write 1_000_000_000 instead of 1000000000.

like image 139
Boann Avatar answered Oct 07 '22 07:10

Boann