According to Swing tutorial:
Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.
But what are these Swing component methods that are labelled "thread safe"? Are there actually any?
Is there a complete list of thread-safe swing methods? (The thread-safe Swing methods seems to be quite rare, so such list can't be too long...)
No, Java Swing components are not thread-safe in Java.
Most Swing object methods are not "thread safe". This means that if those (non thread safe) method are invoked from multiple threads this could result in thread interference or memory consistency errors. Only thread safe methods can be safely invoked from any thread.
A method will be thread safe if it uses the synchronized keyword in its declaration.
So, it's considered to be thread-safe and can be safely called by multiple threads at the same time. All threads can safely call the factorial() method and will get the expected result without interfering with each other and without altering the output that the method generates for other threads.
Google taught me that at least those are threadsafe. Here's an overview for the case that the link get broken again:
JTextPane
replaceSelection()
insertComponent()
insertIcon()
setLogicalStyle()
setCharacterAttributes()
setParagraphAttributes()
JTextArea
insert()
append()
replaceRange()
JTextComponent
replaceSelection()
setText()
print()
getPrintable()
UndoManager
DefaultStyledDocument
insert()
setLogicalStyle()
setCharacterAttributes()
setParagraphAttributes()
StyleContext
addAttribute()
addAttributes()
removeAttribute()
removeAttributes()
reclaim()
AbstractDocument
render()
remove()
insertString()
createPosition()
PlainDocument
insertString()
HTMLDocument
setParagraphAttributes()
But what are these Swing component methods that are labelled "thread safe"?
Most Swing components' methods are NOT thread safe. But some are. To find out which ones, you have no option but to peruse the javadocs for your target components. A carefully constructed google search might quicken the process.
Are there actually any?
Yes there are indeed. Generally speaking, if you are working with Swing components, it is likely that you are going to have to invoke both thread-safe and non-thread-safe methods. Since most methods are non-thread-safe, I prefer to err on the side of caution, and perform all actions on them in a thread-safe manner anyway.
HTH
Not exhaustive list.
DefaultStyledDocument:
javax.swing.text.AbstractDocument:
javax.swing.undo.UndoManager:
Class is threadsafe
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