Which Swing component methods are thread safe?
Asked Answered
H

5

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

Helminthic answered 25/11, 2009 at 12:23 Comment(1)
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....Bluestone
P
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()



Peripatetic answered 25/11, 2009 at 12:42 Comment(5)
You're welcome. Here's an useful link anyway: googleguide.com/using_advanced_operators.htmlPeripatetic
@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.Peripatetic
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?Sloat
Some of the info is outdated. JTextArea.append is no longer thread safe in java 7.Luthern
@Jarekczek: I've added a Java 7 update here.Octillion
E
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

Empathic answered 25/11, 2009 at 12:49 Comment(2)
@Peripatetic Did not! Consider the fact that it takes a couple of minutes to type an answer before you jump to conclusions.Empathic
Wew. nice everyone! that's a great info for me. since now i'm trying to do work in SWING. :DIrritable
C
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.

Curmudgeon answered 18/10, 2010 at 12:16 Comment(0)
C
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

Cardin answered 25/11, 2009 at 12:46 Comment(3)
Yes, it's the implicit answer, but it still isn't a list of thread safe methods.Helminthic
You asked "are there any" and I provided an example. Um.Cardin
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.Floorwalker
O
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()

Octillion answered 12/4, 2013 at 19:12 Comment(5)
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)Egyptology
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.Egyptology
@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, I chose to focus in the list of potential upward migration headaches as the ones needing review.Octillion
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 bugs.openjdk.java.net/browse/JDK-4765383 for example.Griffie
@Holder: I agree; updated, and thanks for the citation.Octillion

© 2022 - 2024 — McMap. All rights reserved.