Dhaivat Pandya Dhaivat Pandya - 10 days ago 5
Java Question

JTextArea thread safe?

I have some code that does some initialization (including making a

JTextArea
object), starts three separate threads, and then these threads try to update the
JTextArea
(i.e.
append()
to it), but its not working at all. Nothing shows up on the
JTextArea
(however, during the initialization, I print some test lines onto it, and that works fine). What's going on? How can I fix this? Also, each of those threads sleeps a random amount of time every time it has to update the
JTextArea
.

Sorry I haven't provided any code, its all spread out over several files.

Answer

Although I believe the API has stated that JTextArea#append(...) is thread safe, I've heard of problems with it and would recommend that this only be called on the EDT. The classic example of this is to use a SwingWorker and append to the JTextArea in the process method by calling publish.

For me, it'll be hard to make any specific suggestions to you though without code. I do have to wonder though if you're putting the EDT to sleep somewhere in your code.

Edit: as per your comment check out this tutorial: Concurrency in Swing


Edit 2: as per comment by Tim Perry, loss of thread safety and the reasoning behind this has been posted in this Java bug and which has to do with this line of code where text is added to the JTextArea's Document:

doc.insertString(doc.getLength(), str, null);

The line decomposes into two lines:

  1. int len=doc.getLength();
  2. doc.insertString(len,str,null);

The issue is that a problem can occur if the Document, doc, changes between lines 1 and 2, especially the Document length.