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];
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 .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With