Search code examples
javaswingdocumentjtextarea

JTextArea consumes a lot of memory


I having some memory issue with Java and Swing. I have a JTextArea (same issue with JTextPane) that I use to redirect stdout from an C++ executable. And because I'm outputting a lot of stdout, JTextPane is consuming a lot of space. In any case, I boiled it down to the following code, all in Java.

private javax.swing.JTextArea jtextareastdout;
....

for (int i = 0; i < 200000; i++) {
    String randomstr = UUID.randomUUID().toString();

    jtextareastdout.setText(randomstr);  //<tag_memory>
    if (i % 100 == 0)
        System.gc(); //<tag_no_help>
}

The above code consumes 100MB. With tag_memory line commented out, a lot less (30MB with all my other code & UI). How can I reduce Java's memory usage? Currently using Java 7 update 4.

Thanks in advance.


Solution

  • I just don't understand where all the memory is going.

    PlainDocument tells the story: either one or two 16-bit code units per code point, a map of line starts and all the impedimenta needed to make it editable. For read-only viewing, I'd use redirection: yourprogram 2>&1 > view. In Java, you could read from stdin into a List<String>, with one String per line, and view it with a JTable. The default renderer is quite efficient. There's a related example here.