java. Lang. outofmemoryerror: Java heap space when initializing arrays

I tried to initialize a Boolean array whose size is a 10 bit integer It continues to throw OutOfMemoryException I have increased the size of eclipse heap space from 256 to 1024 Is there anything I don't want to do?

int size = 1000000000;
boolean[] primesList = new boolean[size];

Solution

Using Java util. BitSet, compared with Boolean array, will occupy one eighth of the space

The reason that Boolean array elements occupy one byte instead of one bit is that (most) CPU architectures cannot provide the ability to read and write a single memory bit directly The smallest unit PC can operate 8 bits The JVM can package these bits together and then modify it. It will read the bit of the byte, modify it and write it back, but this will not work if multiple threads modify the array at the same time

As for your original array, it is 1 billion Boolean values, one byte each, that is, 1 billion bytes or ~ 954 MB So a 1024 MB heap should be enough (?) Maybe it can't find enough contiguous memory blocks, or you don't set the memory parameters correctly Print runtime getRuntime(). Maxmemory() to find the maximum heap size that Java is using For 1024 MB, the parameter should be - xmx1024m

Final note: starting with Java 7, you can use underscores in numbers to make them more readable So you can write 1_ 000_ 000_ 000 instead of 1000000000

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>