I'm using Swing and I have a JFrame containing a few JPanels, and inside one of them there is a JTextArea.
The JTextArea content is set when an user clicks on a certain menu (ActionListener.actionPerformed(populate())).
The content is taken from a 30MB text file:
private void populate () {
StringBuilder strB = new StringBuilder();
try {
FileReader fr = new FileReader("file30mb.txt");
BufferedReader br = new BufferedReader(fr);
String strLine;
while ((strLine = br.readLine()) != null) {
strB.append(strLine).append(System.getProperty("line.separator"));
}
fr.close();
br.close();
} catch (IOException e) {
System.err.println(e);
}
jTextArea1.setEditable(false);
jTextArea1.setText(strB.toString());
jTextArea1.setCaretPosition(0);
}
This process takes a lot of memory usage, about 200MB.
There is another menu and when an user clicks on it the JTextArea is cleared (basically it calls a method that does jTextArea1.setText(null)). The event is handled the same way of before: ActionListener.actionPerformed(free()).
So when the JTextArea is empty I expect that the memory usage is lower than before... But unfortunately it's not true. If I go in the task manager I see the same memory usage of before (about 200MB), but the JTextArea is empty!
What am I missing?
EDIT I also tried this:
jTextArea1.setText(strB.toString());
jTextArea1.setText("");
Runtime r = Runtime.getRuntime();
r.gc();
System.out.println(jTextArea1.getDocument().getLength()); // prints "0"
But it still takes 200MB of memory.
EDIT 2 If I remove the "GUI part" (I mean jTextArea1.setText() etc.) it still takes a lot of memory. It should take "0 memory" because I don't write anything in the JTextArea, but I just read a text file and then do nothing. Am I wrong?
Few reasons:
garbage collection runs periodically, it won't free memory immediately
JVM process memory and heap memory usage are two distinct things. Enable verbose GC logging or connect to your application using jconsole
/jvisualvm
and check real heap usage. Run GC manually
Is Ctrl + Z still working, allowing you to restore previous (30 MB) contents? You get the idea...
If none of these are right, use memory profiler like Eclipse MAT to find out what holds a reference to this huge object (you'll find char[]
of 60 MB size).