3

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
jobobo
  • 389
  • 5
  • 17
  • Yep, `JTextArea` has a lot of features, too; some you may not need. What are your actual requirements? – trashgod Jul 03 '12 at 01:03
  • I mostly want to show my stdout (and stderr) from my c++ program. I just don't understand where all the memory is going. – jobobo Jul 03 '12 at 01:04

1 Answers1

5

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • I need to redirect so that I can read the info coming from stdout/stderr. JTable? Never considered it, but maybe that's a way to go. For my code above, I somehow thought that overwriting my previous string (via .setText()) would free up the previous string for garbage collection. The memory just keeps growing as if it's leaking memory. Any clue on making the above code work? Thanks. – jobobo Jul 03 '12 at 07:43
  • You'll need to profile your actual code to see if anything else can be done. If your don't use `JTable`, you'll want to emulate it's use of the flyweight pattern for rendering. – trashgod Jul 03 '12 at 14:51
  • Yes, `jvisualvm` is included with most Oracle distributions; NetBeans uses it or a variation. – trashgod Jul 12 '12 at 16:08