21

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?


Update / bounty:

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...)

aioobe
  • 413,195
  • 112
  • 811
  • 826
Joonas Pulakka
  • 36,252
  • 29
  • 106
  • 169
  • 2
    The question suggests to me that you are trying to do manipulate a Swing GUI from more than one thread? If so, you might want to rethink your design, as it should always be possible to ensure that all the Swing interactions only happen from one thread as long as you handle offloading of work to other threads correctly e.g. with some form of work queue. If you do this, you won't need to worry about Swing thread safety.... – mikera Oct 18 '10 at 00:16

5 Answers5

20

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()





  • StyleContext
    • addAttribute()
    • addAttributes()
    • removeAttribute()
    • removeAttributes()
    • reclaim()



BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 2
    You're welcome. Here's an useful link anyway: http://www.googleguide.com/using_advanced_operators.html – BalusC Nov 25 '09 at 13:53
  • 1
    @Gili: I fixed the link. Just substitute the old `java.sun.com` URL by the about half-year old `download.oracle.com`. Instead of downvoting you could also just edit the answer. The bad link was namely completely unintentional. – BalusC Jan 03 '11 at 16:39
  • Oh, setText is thread safe on JTextComponent stuff. That's interesting :) Means that in a lot of cases I don't have to use the EDT anymore. I wonder however, if you use an unofficial LAF does it remain thread-safe? – Chris Dennett Jan 03 '11 at 16:45
  • 1
    Some of the info is outdated. `JTextArea.append` is no longer thread safe in java 7. – Jarekczek Oct 08 '12 at 07:21
  • 1
    @Jarekczek: I've added a Java 7 update [here](http://stackoverflow.com/a/15979112/230513). – trashgod Apr 12 '13 at 19:16
7

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:

  • protected void insert(int offset, DefaultStyledDocument.ElementSpec[] data) throws BadLocationException
  • public void setLogicalStyle(int pos, Style s)
  • public void setCharacterAttributes(int offset, int length, AttributeSet s, boolean replace)
  • public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace)

javax.swing.text.AbstractDocument:

  • public void render(Runnable r)
  • public void remove(int offs, int len) throws BadLocationException
  • public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
  • public Position createPosition(int offs) throws BadLocationException

javax.swing.undo.UndoManager:
Class is threadsafe

bguiz
  • 27,371
  • 47
  • 154
  • 243
  • 3
    @BalusC Did not! Consider the fact that it takes a couple of minutes to type an answer before you jump to conclusions. – bguiz Nov 25 '09 at 22:42
  • Wew. nice everyone! that's a great info for me. since now i'm trying to do work in SWING. :D – gumuruh Apr 20 '12 at 02:59
5

For a list of classes with the comment in the javadocs & src files "is thread safe" returns the following

JEditorPane
JTextArea
AbstractDocument
DefaultCaret
DefaultStyledDocument
JTextComponent    
PlainDocument
StyleContext    
HTMLDocument
UndoManager

This is not saying that there are others documented or undocumented within the src that are thread safe.

It strikes me as a rather strange question but I would treat most components as not being threadsafe and since Swing is a single threaded model and all updates need to happen on the event dispatcher thread this is pretty easy to do.

Shawn Vader
  • 12,285
  • 11
  • 52
  • 61
4

In Java 7, some methods of the view components rooted in JTextComponent had been incorrectly marked thread safe; they are now unmarked or correctly marked as not thread safe. A typical workaround using EventQueue.invokeLater() is shown here. The remaining model-related methods, listed here and below, should be reviewed critically going forward for the reasons outlined here. JTextArea::append is a concrete example.



  • JTextPane
  • replaceSelection()
  • insertComponent()
  • insertIcon()
  • setLogicalStyle()
  • setCharacterAttributes()
  • setParagraphAttributes()

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • hmm ... why? Just looked at methods of JTextComponent, the first two don't guarantee being thread safe and the printing related methods are blocking the calling thread. Afair (didn't re-check), nowadays nothing is thread-safe except repaint and revalidate (which guarantee to post the request onto the EDT if necessary) – kleopatra Apr 12 '13 at 22:02
  • ohh ... maybe I misread your intention: it's kind of the old list minus the methods listed here? If so, it might be less confusing (to me, at least :) to list the methods that are still documented to be thread safe. – kleopatra Apr 12 '13 at 22:10
  • @kleopatra: I can't disagree—it's confusing! I was looking for a common thread (no pun intended:-), and it appears to be the view components that were affected. Rather than pre-empt the [original answer](http://stackoverflow.com/a/1796687/230513), I chose to focus in the list of potential upward migration headaches as the ones needing review. – trashgod Apr 12 '13 at 23:38
  • 1
    These methods were not “previously thread safe”, their documentation wrongly claimed a thread safety and has been fixed to accommodate the actual implementation (which did not change). See https://bugs.openjdk.java.net/browse/JDK-4765383 for example. – Holger May 10 '22 at 16:22
  • @Holder: I agree; updated, and thanks for the citation. – trashgod May 10 '22 at 16:46
4

But you already have the answer: only those methods which are specifically documented as being thread-safe in the method JavaDoc, are threadsafe! this is from JTextComponent.setText

 * This method is thread safe, although most Swing methods
 * are not. Please see 
 * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How
 * to Use Threads</A> for more information.     

If the method documentation doesn't say it's safe, then it isn't safe: access to the JavaDoc is therefore critical when coding against Swing

oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • 1
    Yes, it's the implicit answer, but it still isn't a list of thread safe methods. – Joonas Pulakka Nov 25 '09 at 13:00
  • You asked "are there any" and I provided an example. Um. – oxbow_lakes Nov 25 '09 at 14:05
  • There are also methods which are not documented to be thread safe, but which can be called from other threads. At least that's what I think. E.g. the `dispose()` method in the java.awt.Window class can be called by any thread, because the method itself creates a runnable which is sent to the EDT. Sure, you might argue that `dispose()` is a AWT method and not a Swing method, but it's used often enough in Swing to be worth mentioning. – Alderath Apr 03 '12 at 09:04