Trying to understand "thread-safe" w/ swing components

The other day there was a big hullabaloo about some code I posted because I was calling JLabel.setText from a thread that wasn't the ui thread. On the other hand, this thread was the only thread making changes to the JLabel. My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?
Second question - JLabel.setText() is essentially setting data in the model for JLabel, which then gets picked up and displayed the next time the GUI thread paints it. So if it's not safe to update a JLabel's model, I assume its never safe to update any data that also is being displayed visually. So for instance, if I was showing some database table data in a JTable, I should do the update in the UI thread - probably not. But what is the distinction?
Third question - what swing components and what operations need to be run on the UI thread to call your program "thread-safe". Validate? setSize()? setLocation()? add? remove? Is there anything that can be called on swing components from a non-ui thread?
Edited by: tjacobs01 on Nov 2, 2008 8:29 PM

tjacobs01 wrote:
My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?This is not true. As I mentioned in that hullabaloo thread, the Java Memory Model allows threads to cache values of variables they use. This means that values written by one thread are not guaranteed to ever be visible to other threads, unless you use proper synchronization.
Take the following example:
import java.util.concurrent.TimeUnit;
public class ThreadExample {
    static class Foo {
        private String value = "A";
        public String getValue() {
            return value;
        public void setValue(String value) {
            this.value = value;
    public static void main(String[] args) {
        final Foo foo = new Foo();
        Thread writer = new Thread() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    foo.setValue("B");
                } catch (InterruptedException e) {
                    e.printStackTrace();
        Thread reader = new Thread() {
            @Override
            public void run() {
                try {
                    TimeUnit.MINUTES.sleep(1);
                    System.out.println(foo.getValue());
                } catch (InterruptedException e) {
                    e.printStackTrace();
        writer.start();
        reader.start();
}Here two different threads both access the same Foo instance, which is initialized with a value of "A". One thread, the writer, sleeps one second, and then sets foo's value to "B". The other thread, the reader, sleeps one minute (to avoid race conditions) and then prints foo's value to System.out. It may seem obvious that the reader thread will read the value "B", but this is in fact not guaranteed to be true. The reader thread may never see the value that was written by the writer thread, so it may very well read the old value "A".
(If you run the code you will probably see "B" printed out, but again, this is not guaranteed behavior.)
A simple way to fix this is to synchronize access to the mutable state that the two threads share. For example, change the class Foo to
    static class Foo {
        private String value = "A";
        public synchronized String getValue() {
            return value;
        public synchronized void setValue(String value) {
            this.value = value;
    }It's for this same reason that you often see the use of a volatile boolean as a control flag for stopping threads, rather than a plain old boolean. The use of volatile guarantees that the thread you want to stop actually sees the new value of the flag once it has been set by another thread.
Here is an article that touches some of this stuff:
[http://www.ibm.com/developerworks/java/library/j-jtp02244.html]
I also highly recommend the book "Java Concurrency in Practice" (one of the authors of which, David Holmes, sometime hangs out on the Concurrency forum here, I believe).
Edited by: Torgil on Nov 2, 2008 9:01 PM

Similar Messages

  • I am trying to understand if cloud supports SOA components deployment , if so how can we achieve it.

    Hi All
    I am trying to understand if cloud support SOA components deployment like BPEL, Mediator etc.., It will be great help if someone can confirm this

    Photoshop does not keep profiles anywhere.
    Profiles are managed by the OS.
    Photoshop shows the available profiles in it's UI, and gets the list of available profiles from the OS.
    What does Hot Press Birght Paper mean?
    That the profile applies to a particular paper, probably called "hot press bright" paper.
    Yes, you will have a profile for each printer and type of paper -- you have to in order to describe how the image will appear on each printer and type of paper.

  • Trying to understand threads; interesting synchronize question

    Ladies and Gentlemen,
    what would happen if:
    class c {
    public synchronized void a() {
    //do some stuff
    b();
    public synchronized void b() {
    // do some stuff
    this should cause a deadlock situation, should it not? The compiler doesnt complain when I try this.
    Can someone confirm if this is correct:
    any class method can be synchronized; it doesnt have to be a method in a thread you ahve created. Presumable, this method and its object are being manipulated by threads, so synchronization of data is necessary. I have a program that has multiple threads. Each thread get a reference to manager object (there is one object for all the threads, not one for each). Each thread has its own instance of an analysis object. The analysis object takes teh reference to the manager object in its constructor, so the end result is mulitple threads each have their own analysis object, and all of these objects point to one manager object. I want the methods of the manager object to be synchronized to avoid read/write conflicts and inconsistencies.
    Thank you in advance

    You are right it is not officially deadlock. but it
    is a situation that will produce an error if one is
    not careful. b is called in a, and they both require
    a lock, so the processing in b cant be done while a is
    running. No, I'm telling you that is not the case. You can call b() from a() because if a thread is in a() it already has the lock needed to call b(). There is no possiblity of deadlock with the code you have written.
    In order for a deadlock to be possible, you'd need to do something like this:
    class Example
       final lockObjectA = new Object();
       final lockObjectB = new Object();
       void a()
          synchronized(lockObjectA)
              b();
       void b()
          synchronized(lockObjectB)
              a();
    }

  • Using IPortalComponentProfile: Thread safe variables?

    Hi guys!
    I’m trying to understand (deeply) the framework used by the EP and I found something that disturb me like crazy… the use of the IPortalComponentProfile.
    I just don’t get it The profile suppose to hold variables for your iView instance right? Now, if you are trying to have thread safe variables in your iView  (which is desirable) why you have to used the “application” scope (in a JSP page) to retrieve those variables??? As you know, the application object in a JSP page refers to the ServletContext: All those variables are visible to the entire application which is completely the opposite to the thread safe concept… Am I wrong? Did I miss something?
    If you guys have the clue about this please let me know…
    Thanks in advance!
    Bye.
    Al

    Here's the answer taking from the Portal docs:
    "Except the scope option APPLICATION all the other scope options follow the JSP specifications from Sun Microsystems. <b>The option APPLICATION had to be modified to meet the requirements for a portal.</b> The standard recommendation of APPLICATION would allow access to a the bean through out the whole portal (it would be located in the "Web Application" shell if you look at the following overview chart). In the portal the sphere for APPLICATION is defined as the portal component. This gives the portal component control over the bean but the bean cannot be accessed by other users or other applications of the same user."
    Al.

  • Is there a Thunderbird manual? I'm trying to understand all the View/Threads options.

    I'm learning Thunderbird, hoping to adopt it as my mail client (can't keep Eudora afloat any more). The forums are not efficient for learning it. Right now I'm trying to understand all the View/Threads options, but tomorrow it will be something else.

    Thanks, those are helpful. The first one doesn't explain threads options but it led me to https://github.com/protz/GMail-Conversation-View/wiki/What-is-threading, which told me to do View > Sort by > Threaded (I had only tried View > Threads > ...). It also explains threading by message ID, whereas Eudora seems to do it only by subject line.
    Neither reference explains the options under View > Threads > ... but I'll figure it out by trial & error.
    The second reference led to http://www.nidelven-it.no/documentation/thunderbird/introduction-to-thunderbird, which also looks helpful.

  • What does, "swing is not thread safe." mean?

    can anyone explain what that means in detail?

    [Google can|http://letmegooglethatforyou.com/?q=swing+is+not+thread+safe+tutorial]
    For better response, you may wish to ask a specific question that's answerable without having to write a book chapter.

  • How can i understand swing components?

    hi
    i am tonmoy. i have some question about swing component
    i,e JTextField,JListBox JTable etc.
    1. i have made a class name StyledDOcument extends
    DefaultStyledDocument so i can access any public method of
    DefaultStyledDocument. but my problem is that i cannot understand
    which method is implicitly called and whcih are not.
    for example InsertString(int offs, String str, AttributeSet a)
    is internally called because if i dont override it or call it using
    super.insertstring(), it will be called internally everytime i press
    char from keybord.
    so i think there are many method of swing components that are called
    internally but by reading java doc i can't understand
    which method is internally called and which are not.
    so plese answer my questions in details.
    thank you

    Tutorials, Teachers, and books are all good ways to learn these things.

  • Is it possible to create Thread for Swing Components or for JApplet?

    Can i create a Thread by extending Thread class or implementing Runnable interface for Swing Components?
    Can i create a Thread by extending Thread class or implementing Runnable interface with JApplet?
    thanks

    Does your website live on a Windows server? The above link you posted will require a Windows server for that to work but if you do, then you should be able to just follow the links instructions.
    If your site is not on a Windows server (maybe it's on Linux?) then you would most likely need a PHP solution - something like this: http://www.w3schools.com/php/php_mail.asp. Depending on your host, they might actually have a ready-built form script for you to use so it might be best to ask them first.
    You might also want some kind of validation to ensure you receive the correct information so something like jQuery Validate could work.

  • Swing thread safe ?

    Hi
    Are swing comonents are thread safe ?
    If i am not wrong the thread safe objects are those whose data changes are predictable ( i mean no race condition)
    Is this correct ?
    I had worked on multithreaded application in MFC where we used Message queues for hadling the multithreading
    Can i use the same logic in java also ? If yes can anybody help me how can i do it
    Thanks in advance

    The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html]Using Threads explains the concept of "Thread Safe".

  • Swing isn't thread safe, what about AWT?

    Since Swing isn't really thread safe what does that mean for AWT? Is AWT thread safe? Also if it is doesn't that mean one should use AWT over Swing since AWT is thread safe?

    Trizi wrote:
    jverd wrote:
    Trizi wrote:
    [http://forum.java.sun.com/thread.jspa?threadID=5282846&tstart=0|http://forum.java.sun.com/thread.jspa?threadID=5282846&tstart=0]
    There ya go duffy the hom^oYou say that is if being gay were a bad thing. So, besides being an obnoxious fuckhead, you're also a homophobic troglodyte? Man your fiancee must be a real winner to have picked you. My guess is that she's either a sheep, a blow-up doll, or someone you've got bound and gagged in your basement.Now from what everyone is saying that I don't have anything original...
    You don't either, too much "Silence of the Lambs" maybe?Dude, try speaking English.
    By the way, I am sure if I was a troglodyte I would be in a museum, also I have homosexual friends, sorry not homophobic, I just found a good ting to his name and figured I'd exploit it.. Just like I'm exploiting your pathetic intelligence.You really need help if you think the above makes any sense or any point.

  • Are the APIs of java.swing.Timer thread-safe?

    As the title.

    They are safe for use with the event thread, as the actionPerformed method is invoked on the event thread,
    so you can make UI changes from your actionPerformed without fear.
    That is their only thread-related-ness, so other than that, I would think they are not thread safe in general.
    : jay

  • Thread safe do-all class

    Hi,
    I'm new to Java programming and I've read through the forums and the numerous technical documents Sun has provided on how to make a GUI thread-safe. With what I've been able to understand, I created some template classes to handle the proper creation of JFrames, so I don't have to worry about playing with threads all the time. (I am operating under the assumption that invokeLater should handle the creation of all frames, not just the first window of the application).
    Since I'm not completely confident I've grasped the point, I was wondering if someone could look at this code to see if I've got the right idea. Your help would be much appreciated.
    Test.java
    import frames.*;
    public class Test
         public static void main(String args[])
              FrameOptions frameOpts = new FrameOptions("Options Window", 300, 400, true);
    frames\FrameOptions.java
    package frames;
    public class FrameOptions extends FrameTemplate
         public FrameOptions(String title, int width, int height, final boolean visible)
              super(title, width, height);
              javax.swing.SwingUtilities.invokeLater     (     new Runnable()
                                                 public void run()
                                                      createAndShow(visible);
         public void createAndShow(boolean visible)
              //Add all Swing components here.
              finishCreateAndShow(visible);
    frames\FrameTemplate.java
    package frames;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    public class FrameTemplate extends JFrame
         public FrameTemplate(String title)
              super(title);
         public FrameTemplate(String title, int width, int height)
              super(title);
              doSize(width, height);
         private void doSize(int width, int height)
              Dimension d = new Dimension(width, height);
              setMinimumSize(d);
              setPreferredSize(d);
         protected void finishCreateAndShow(boolean visible)
              pack();
              setVisible(visible);
    }

    OK, makes sense now.
    For anyone else who may be new and wondering about this, this can be summed up as follows.
    Summary 1:
    If you create new frames from things such as menu events, you do not need to use invokeLater. Events are automatically done in the GUI thread/event dispatching thread. But if you're spawning these things from main() (or anything else not running in the EDT), you do.
    If you're ever unsure of which thread a block of code is running in, just drop a System.out.println(javax.swing.SwingUtilities.isEventDispatchThread()); into it.
    Summary 2:
    Don't use those classes I wrote. They're rather pointless unless you're spawning all of your frames from main, which I suspect most people would not be doing.
    Thanks for the clarification.
    public static void main(String args[])
    is run in a separate thread (separate from the GUi
    i thread). So if you need to do painting or other
    swing stuff from inside the main method, just use an
    invoke later. If you create a new frame from the GUI
    thread, you don't need to invoke later. Only if you
    do it from the main method (or some other non-GUI
    thread). Hope that helps

  • What does it mean to be "thread safe"?

    What does it mean to be "thread safe"?
    I am working with a team on a project here at work. Someone here suggested that we build all of our screens during the initialization of the application to save time later. During the use of the application, the screens would then be made visible or invisible.
    One of the objections to that idea was that the swing components (many of which we use) are not thread safe. Can anyone tell me what the relevance of that is?
    Thanks

    To understand why Swing is not thread safe you have to understand a little bit of history, and a little bit of how swing actually works. The history(short version) is that it is nearly impossible to make a GUI toolkit thread safe. X is thread safe(well, sorta) and it's a really big mess. So to keep things simple(and fast) Swing was developed with an event model. The swing components themselves are not thread safe, but if you always change them with an event on the event queue, you will never have a problem. Basically, there is a Thread always running with any GUI program. It's called the awt event handler. When ever an event happens, it goes on an event queue and the event handler picks them off one by one and tells the correct components about it. If you have code that you want to manipulate swing components, and you are not ON the awt thread(inside a listener trail) you must use this code.
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        // code to manipulate swing component here
    });This method puts the defined runnable object on the event queue for the awt thread to deal with. This way changes to the components happen in order, in a thread safe way.

  • The Single Threaded Nature of Swing

    I am designing a program that uses the basic <i>Model View Controller</i> design pattern. The controller allows you to manipulate the <i>Model</i> and the <i>Views</i> then display a graphical representation of the <i>Model</i>.
    Any way I want to have several different, independent <i>Views</i> of my <i>Model</i>. So I thought; well since the <i>Views</i> are only dependent on the <i>Model</i> I should be able to have the <i>Model</i> raise an event to alert the <i>Views</i> to update their drawing appropriately. Naturally since all the <i>Views</i> are independent I would like them to draw in their own threads, but since Swing is not thread safe it seams that i wont be able to do that.
    As a potential solution I am considered having each <i>Views</i> first create a graphics object that has all the new drawing information, then make a call to repaint through Swings Event Dispatch Thread and and have the component paint method simply BLIT from the pre-rendered graphics object into the graphics Object passed in the paint method. This has the advantage of allowing all the <i>Views</i> to do their drawing code concurrent;y and keep the <i>Controller</i> portion responsive since the even dispatch thread will only have to perform a very simple operation for repaints, however since i have no guarantee as to when the Event Dispatch Thread will actually get around to drawing them I winder if latency will be an issue.
    Non the less I can't help but think that in such a situation it would be safe to multi-thread the drawing. I would like to know if any body else has had to do something similar and what kind of approach they took.
    Flaws in my logic or comments regarding my current solution are also greatly appreciated.

    PCP wrote:
    Any way I want to have several different, independent <i>Views</i> of my <i>Model</i>. So I thought; well since the <i>Views</i> are only dependent on the <i>Model</i> I should be able to have the <i>Model</i> raise an event to alert the <i>Views</i> to update their drawing appropriately. Which is how Swing components work internally, so it all sounds good here.
    Naturally since all the <i>Views</i> are independent I would like them to draw in their own threads, but since Swing is not thread safe it seams that i wont be able to do that.It almost sounds as if you are confusing thread safety with not having the ability to interact with different threads. I'm no Graphics expert, but I think that Swing can handle all this as long as you handle Swing right: Do what you need to do in your separate threads, but just remember to only update Swing components on the EDT.
    As a potential solution I am considered having each <i>Views</i> first create a graphics object that has all the new drawing information, Or perhaps a graphics object derived from a BufferedImage object?
    then make a call to repaint through Swings Event Dispatch Thread and and have the component paint method simply BLIT from the pre-rendered graphics object into the graphics Object passed in the paint method. This has the advantage of allowing all the <i>Views</i> to do their drawing code concurrent;y and keep the <i>Controller</i> portion responsive since the even dispatch thread will only have to perform a very simple operation for repaints, however since i have no guarantee as to when the Event Dispatch Thread will actually get around to drawing them I winder if latency will be an issue.What is the frequency with which you are calling repaints? Have you tried this and found that Swing degrades your program's responsiveness? Again, I'm no graphics expert (where's Darryl, Hiwa, Morgalr when you need them?), but have you considered using active rendering instead of the typical passive rendering?
    Non the less I can't help but think that in such a situation it would be safe to multi-thread the drawing. I would like to know if any body else has had to do something similar and what kind of approach they took. Flaws in my logic or comments regarding my current solution are also greatly appreciated.Whatever happens, please let us know the outcome. Good luck!

  • GetTreeLock during constructor for swing components

    I've noticed some dead locks in our application that are showing up in the call to getTreeLock that exists in the constructor for various JComponents. Specifically, the updateUI method winds up calling validateTree.
    I thought it was OK to construct JComponents from any thread, this suggests it is not.
    Has anyone else experienced this?

    It goes like this:
    On win32, thread 0 is our windows message pump. If dispatching one of our messages results in a call from C into Java that constructs a JComponent, we call getTreeLock from thread 0.
    Imagine that at the same time, the awt event disptatch thread is trying to show a frame. Since the awt event dispatch thread is part of our process, when the native implemention of the frame calls SendMessage to show the frame, the call to SendMessage blocks until thread 0 calls GetMessage.
    Since thread 0 is now blocking waiting for synchronized(getTreeLock()) to return and the awt event dispatch thread has the tree lock - fetched while executing the show() method - we are in a dead lock.
    This is not a problem with AWT components, only swing components.
    The stack looks like this:
         at java.awt.Component.getTreeLock(Component.java:811)
         at java.awt.Container.invalidateTree(Container.java:1116)
         at java.awt.Container.setFont(Container.java:1148)
         at javax.swing.JComponent.setFont(JComponent.java:2310)
         at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:89)
         at javax.swing.plaf.basic.BasicButtonUI.installDefaults(BasicButtonUI.java:124)
         at com.sun.java.swing.plaf.windows.WindowsButtonUI.installDefaults(WindowsButtonUI.java:63)
         at javax.swing.plaf.basic.BasicButtonUI.installUI(BasicButtonUI.java:60)
         at javax.swing.JComponent.setUI(JComponent.java:449)
         at javax.swing.AbstractButton.setUI(AbstractButton.java:1616)
         at javax.swing.JButton.updateUI(JButton.java:119)
         at javax.swing.AbstractButton.init(AbstractButton.java:1952)
         at javax.swing.JButton.<init>(JButton.java:109)
         at javax.swing.JButton.<init>(JButton.java:64)
    It seems like we could simply have the invalidateTree method return early if there is no parent or there are no children or somesuch.
    A work around we've done is to have the updateUI method delegate to the event dispatch thread. This is a drag as we need to subclass all the JComponents and make sure developers use the safe subclass.

Maybe you are looking for

  • Runtime Error in Record INsertion to an Infotype

    Hi all, I have created an infotype PA9035. In that i want to insert records with value Data:  WA_PA9035 TYPE PA9035.   WA_PA9035-PERNR  = P_PERNR.   WA_PA9035-ZZKOKRS = V_KOKRS.   WA_PA9035-ENDDA = '99991231'.   WA_PA9035-BEGDA = SY-DATUM. I used the

  • I use a yahoo email as my Apple ID. How can I use an alias with no one knowing

    How do I know if my daughter is using an alias for her iCloud/Apple id.

  • Subnet vs VLAN, L2 broadcast and L3 broadcast

    Hi all, I understand what are subnets and VLANs in which subnet breakup a network into different smaller segment, whereas VLAN is the logical breaking of a physical switch into several logical ones. By right, each subnet and VLAN belongs to its own b

  • IDOC ABAP-PI Port Function Module not called

    HI all, i am using a scenario where i am sending (outbound) idocs via abap proxy to PI. I have assigned the function module to the abap-pi port. when i am trying to send a test idoc via we19, i get the message "IDoc '0000000000198029' transferred to

  • Lion-Outlook 2011 sync

    I am thinking of purchasing Office 2011 for Mac.  I run Mac OS 10.7.3 (lion) on a MacBook.  I also have an iCloud account presently using Apple Mail.  I would like to be able to use Outlook 2011 and sync my email, contacts and calendars.  Is this goi