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
.