简体   繁体   English

对于包含数百万条记录的循环 - java.lang.OutOfMemoryError:Java堆空间

[英]For Loop with millions of records - java.lang.OutOfMemoryError: Java heap space

I'm getting OutOfMemoryError: Java heap space for the following code: 我得到OutOfMemoryError:以下代码的Java堆空间:

StringBuilder obj= new StringBuilder("");
InputStream in = new FileInputStream(new File(file));
br = new BufferedReader(new InputStreamReader(in), 102400);
for (String line; (line= br.readLine()) != null;) {
    for (i = 0; i < 3; i++) {
        for (j = 1; j < 5; j++){ 
            obj.append(line.charAt(j)); 
        }
    }   
    hashMap.put(obj.toString(), someValue);
    obj.setLength(0);
}

but, 但,

StringBuilder obj= new StringBuilder("");
InputStream in = new FileInputStream(new File(file));
br = new BufferedReader(new InputStreamReader(in), 102400);
for (String line; (line= br.readLine()) != null;) {
    obj.setLength(0);
    for (i = 0; i < 3; i++) {
        for (j = 1; j < 5; j++){ 
            obj.append(line.charAt(j)); 
        }
    }   
    hashMap.put(obj.toString(), someValue);
}

resolved the error? 解决了错误? What is the issue in placing obj.setLength(0) at the beginning or at the end? 将obj.setLength(0)放在开头或结尾有什么问题?

The Exception: 例外情况:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Unknown Source)
at java.lang.String.<init>(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)

Because threshhold of heapspace is already reached till you put objects in hashmap (last line in your code when its not giving error). 因为已经达到了堆空间的阈值,直到你将对象放在hashmap中(代码中的最后一行没有给出错误)。 Any operation (not only setting the length to zero but any other operation that deals with heap) will cause heapspace to become outOfMemory. 任何操作(不仅将长度设置为零,而是处理堆的任何其他操作)将导致heapspace变为outOfMemory。

Increase heapspace for your java. 增加java的堆空间。

Add -XmX 4096 添加-XmX 4096

If you are really interested with your heap space usage you can run jvisualvm located in your JDK_HOME/bin directory. 如果您真的对堆空间使用感兴趣,可以运行位于JDK_HOME / bin目录中的jvisualvm。

Go to cmd (command line, yes I'm assuming you're on windows ;) ). 转到cmd(命令行,是的,我假设你在Windows上;))。

Then type the following precisely. 然后准确输入以下内容。

java -Xmx4096

Type in 输入

java
to find out all the other things you can do. 找出你可以做的所有其他事情。 I hope this is more clear. 我希望这更清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM