Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing multi-threaded access to JTextArea

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?

like image 526
Luo Avatar asked May 06 '15 00:05

Luo


1 Answers

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.

like image 177
Tim B Avatar answered Nov 10 '22 23:11

Tim B