java.lang.OutOfMemoryError:初始化数组时的Java堆空间 [英] java.lang.OutOfMemoryError: Java heap space while initialising an array

查看:92
本文介绍了java.lang.OutOfMemoryError:初始化数组时的Java堆空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试初始化一个布尔类型的数组,其大小为10位整数.它不断抛出 OutOfMemoryException .我已将eclipse的堆空间大小从256增加到1024.我有什么事要做吗?

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

解决方案

使用 java.util.BitSet ,与使用boolean数组相比,它将在八分之一的空间中打包位.

布尔数组元素占用1个字节而不是1个位的原因是因为(大多数)CPU体系结构不提供直接读取和写入内存的各个位的能力. PC可以操纵的最小单位为8位. JVM 可以将这些位打包在一起,然后修改位,它将读取,修改和写回该字节,但是如果多个线程同时修改该数组,则无法正常工作. >

对于您的原始数组,它是10亿个布尔值,每个1字节,即10亿字节或〜954 MB.因此,一个1024 MB的堆应该足够了(?).可能找不到足够大的连续内存块,或者您没有正确设置memory参数.打印Runtime.getRuntime().maxMemory()的值以找出Java使用的最大堆大小.对于1024 MB,参数应为-Xmx1024M.

最后的注释:从Java 7开始,您可以在数字中使用下划线以使其更具可读性.因此,您可以编写1_000_000_000而不是1000000000.

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];

解决方案

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.

这篇关于java.lang.OutOfMemoryError:初始化数组时的Java堆空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆