OutOfMemoryError即使很多

OutOfMemoryError即使很多

本文介绍了java.lang.OutOfMemoryError即使很多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将2.5GB的txt文件读入我的应用程序。我正在运行Win7 x64并且有43GB的内存可用(64GB)。我尝试使用-Xmx -XX:MaxParmSize -XX:ParmSize等。这些都不会影响错误。我还能尝试什么?这个错误看起来很奇怪,因为我当然有足够的可用堆空间。

I am trying to read a 2.5GB txt file into my application. I am running Win7 x64 and have 43GB of mem available (out of 64GB). I tried playing around with -Xmx -XX:MaxParmSize -XX:ParmSize etc. None of these affect the error. What else could I try? This error seems very odd as I certainly have enough heap space available.

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at java.util.Arrays.copyOf(Unknown Source)
    at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source)
    at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
    at java.lang.AbstractStringBuilder.append(Unknown Source)
    at java.lang.StringBuilder.append(Unknown Source)
    at j.utilities.IO.loadString(IO.java:187)
    at j.utilities.IO.loadString(IO.java:169)
    at city.PreProcess.main(PreProcess.java:78)

我正在运行

java version "1.7.0_09"
Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode)

提前多多谢谢。

==== ========= =答案==============

============== ANSWER ==============

好的,我只是用

StringBuilder sb = new StringBuilder();
for ( int i=1; i<Integer.MAX_VALUE; i++ )
    sb.append("x");

并获得

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at java.util.Arrays.copyOf(Unknown Source)
...

因此,它确实是StringBuilder,它试图构建一个大于Integer.MAX_VALUE的数组。

Thus, it really is StringBuilder which tries to build an array bigger than Integer.MAX_VALUE.

如果感兴趣

StringBuilder sb = new StringBuilder();
int i=1;
try {
    for ( ; i<Integer.MAX_VALUE; i++ )
        sb.append("x");
} catch ( OutOfMemoryError e ) {
    System.out.println(i); // OUTPUT: 1207959551
    System.out.println(Integer.MAX_VALUE); // OUTPUT: 2147483647
}

使用StringBuilder,您可累积1,207,959,550个字符 - 远小于Integer.MAX_VALUE。

With StringBuilder you can accumulate 1,207,959,550 chars - far less than Integer.MAX_VALUE.

推荐答案

您正在尝试分配一个太大的数组。这是因为您正在尝试创建一个非常长的String。由于数组是由整数索引的,因此数组不能超过 Integer.MAX_VALUE 元素。即使您的堆大小非常大,您也无法分配具有超过 Integer.MAX_VALUE 元素的数组,原因很简单,因为您无法使用其索引元素整数。有关更多详细信息,请参阅。

You're trying to allocate an array that is too large. This is because you're trying to create a very long String. Since arrays are indexed by an integer, an array cannot have more than Integer.MAX_VALUE elements. Even if the your heap size is very large, you won't be able to allocate an array that has more than Integer.MAX_VALUE elements, simply because you cannot index its elements using an Integer. See Do Java arrays have a maximum size? for more details.

这篇关于java.lang.OutOfMemoryError即使很多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 01:36