7

I have a multi-threaded Java Swing application.

Several threads will call the method with writing to JTextArea via textArea.append("something"). Should I wrap it like this:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        textArea.append("something");
    }
});

Or it is just a content updating and Swing will do the correct threading itself?

Tim B
  • 40,716
  • 16
  • 83
  • 128
Luo
  • 445
  • 2
  • 10
  • 3
    A call to `JTextArea#append(...)` should be queued onto the Swing event thread to work safest and best. – Hovercraft Full Of Eels May 06 '15 at 01:01
  • 1
    The approach you have is a good start. The question is, do you care in what order the updates occur? If you do, then you have a large problem on your hands ;) – MadProgrammer May 06 '15 at 01:02
  • Actually no. I have an opposite question - do you mean the order of swing displyaing or the order of method calls? The method has a counter, and it it marks messages (logs). But do you mean that Swing can show numerated messages in a wrong order? So, should I use such wrap? – Luo May 06 '15 at 01:06
  • 1
    For [example](http://stackoverflow.com/a/3245805/230513). – trashgod May 06 '15 at 01:25
  • @Luo As already said, you should *definitely* use this 'wrap' as UI widget methods must never be called from any other thread than the event dispatch thread. – isnot2bad May 06 '15 at 21:14
  • This question includes also an answer with the complete source code posted. Where is the problem, then? – Audrius Meškauskas May 10 '15 at 19:54
  • The question was if I need this answer :) – Luo May 12 '15 at 06:09

1 Answers1

1

In general absolutely any updates you do to Swing, and in particular anything that changes the state or layout of a control, should be done from the Swing thread.

In this case you are absolutely right, wrapping each update into an invokeLater is the correct way to do this. You could try updating your own queue or similar but when Swing has already provided just the functionality you need then it makes sense to use it.

See the JTextArea documentation: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html

Where it says

Warning: Swing is not thread safe. For more information see Swing's Threading Policy.

Where it says:

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.

The JTextArea#append method has nothing documented in it saying that it is safe to use from other threads.

Tim B
  • 40,716
  • 16
  • 83
  • 128