I have ask similar question before : Java String Memory Leak
But I was not sure what to ask:
Here is another piece of code I wrote:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class TestString {
public static int readLineXX(BufferedReader br) throws Exception {
String s = br.readLine();
if ( s == null ) return 0;
return 1;
}
public static void main(String args[]) {
while (true) {
try {
FileInputStream fstream = new FileInputStream("bigfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ( readLineXX (br)!= 0) {
//System.out.print(".");
}
br.close();
in.close();
fstream.close();
} catch (Exception e) {
}
}
}
}
Since the String in Java are Immutable, will the String s be garbage collected.
I ran this code for long time using -verbose:gc -XX:+PrintGCTimeStamps -XX:+PrintGCDetails options, It is running fine.
This is small snippet code of my main application where I think is leak and causing OOM.
bigfile.txt is around 1GB.
Yes,
swill be garbage collected. Being immutable does not prevent it from being garbage collected, it just prevents it from being modified.Note that
br.readlLine()will potentially use a large amount of memory if the line is very large. For example, if your text file is 1gb without any line breaks, then it is quite possible forbr.readLine()to consume 2gb, 1gb for the data that is read in, and then 1gb for the created string.