I am not java expert.
My code is reading a file into a String. This code gets executed every 5 minutes.
The size of file varies. Sometimes it is 100 sometimes it is 1000 lines.
I am experience Out Of Memory, after some days.
The question I have is, when my codes goes out of scope of the Reading file function, does Java garbage collect the String?
I am pretty confused by reading on the internet. Some people says it does not get deleted and use StringBuffer.
// Demonstrate FileReader.
import java.io.*;
class FileReaderDemo {
public static void read(BufferedReader br) throws Exception {
long length = 0;
String s;
while (true) {
s = br.readLine();
s += "abcd";
if (s == null) {
break;
}
length += s.length();
//System.out.println(s);
}
System.out.println("Read: " + (length / 1024 / 1024) + " MB");
}
public static void main(String args[]) throws Exception {
//FileReader fr = new FileReader("FileReaderDemo.java");
FileReader fr = new FileReader("big_file.txt.1");
BufferedReader br = new BufferedReader(fr);
String s;
read(br);
fr = new FileReader("big_file.txt.1");
br = new BufferedReader(fr);
read(br);
fr = new FileReader("big_file.txt.1");
br = new BufferedReader(fr);
read(br);
fr = new FileReader("big_file.txt.1");
br = new BufferedReader(fr);
read(br);
BufferedReader in = new BufferedReader(new InputStreamReader(System. in )); in .readLine();
fr.close();
}
}
sis never null where he checks it since he adds "abcd" to it. I thought it would throw an exception but apparently it turns into "nullabcd"