0

I am reading a JSON file using below code and getting java out of memory error:

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(); and warning was resolved. However, the issue of java heap space is stuck.

I even changed my file to a normal text file and added just one sample line to the file, but the issue persists.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • possible duplicate of https://stackoverflow.com/questions/37335/how-to-deal-with-java-lang-outofmemoryerror-java-heap-space-error-64mb-heap – Lokesh Pandey Sep 26 '17 at 11:12
  • No, for the mentioned issue the file size is huge.But in my case, I even tried now with 2 lines file.It just reads first line and throws this error –  Sep 26 '17 at 11:26
  • Did you check the Jiri's answer ? – Lokesh Pandey Sep 26 '17 at 11:33

1 Answers1

3

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. It will just loop until you run out of memory.

You need to put the line = br1.readLine() into the loop:

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.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43