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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With