简体   繁体   English

资源泄漏导致内存不足java堆空间问题

[英]out of memory java heap space issue because of resource leak

I am reading a JSON file using below code and getting java out of memory error: 我正在使用以下代码读取JSON文件,并导致Java内存不足错误:

BufferedReader br1 = new BufferedReader(new FileReader(filename));
try {
StringBuilder sb = new StringBuilder();
String line = br1.readLine();
while (line != null) {
  sb.append(line);
  }
result = sb.toString();
} catch (Exception e) {
  e.printStackTrace();
}

I get below error: 我得到以下错误:

java.lang.OutOfMemoryError: Java heap space
        at java.util.Arrays.copyOf(Arrays.java:3332)
        at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)
        at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:448)
        at java.lang.StringBuilder.append(StringBuilder.java:136)

Later I realized there was a warning of resource leak for buffered reader so I added code br1.close(); 后来我意识到缓冲的读取器存在资源泄漏的警告,因此我添加了代码br1.close(); and warning was resolved. 警告已解决。 However, the issue of java heap space is stuck. 但是,Java堆空间问题仍然存在。

I even changed my file to a normal text file and added just one sample line to the file, but the issue persists. 我什至将文件更改为普通文本文件,并仅向该文件添加了一个示例行,但是问题仍然存在。

This isn't any memory leak, this is infinite loop. 这不是任何内存泄漏,这是无限循环。 You're not updating line in the while loop so it will never be null. 您不会在while循环中更新line ,因此它永远不会为null。 It will just loop until you run out of memory. 它将一直循环直到您用尽内存。

You need to put the line = br1.readLine() into the loop: 您需要将line = br1.readLine()放入循环中:

try (BufferedReader br1 = new BufferedReader(new FileReader(filename))) {
    StringBuilder sb = new StringBuilder();
    String line = br1.readLine();
    while (line != null) {
        sb.append(line);
        line = br1.readLine();
    }
    result = sb.toString();
} catch (IOException | RuntimeException e) {
    // TODO proper exception handling
}

Also note that if your input is potentially very large, you may need to process it sequentially instead of storing it all in a string. 还要注意,如果您的输入可能很大,则可能需要顺序处理它,而不是全部存储在字符串中。

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

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