For Loop with millions of entries - java.lang.OutOfMemoryError: Java heap space
I am getting OutOfMemoryError: Java heap space for the following code:
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);
}
error resolved? What is the problem of placing obj.setLength (0) at the beginning or at the end?
An 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)
+3
source to share
3 answers
Since heap spawning has already been reached until you put the objects in the hashmap (the last line in the code when it doesn't give an error). Any operation (not only setting the length to zero, but any other heap-related operation) will cause the heap space to become outOfMemory.
+1
source to share