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

Similar Messages

  • 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

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

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

  • Swing Threads

    Does anybody know how the threads in a swing application are organized. I noticed, that when i start a swing application more then 10 threads are created. Furthermore, when the "main" thread is terminated after showing the main window (a JFrame window), two windows are displayed. When the main-thread is ran in a loop (while (true) {try{Thread.sleep(100);}catch(Exception x){}), only one window is displayed. So, even if the main thread does nothing, it's necessary.
    Furthermore, i realized that, when starting other threads out from the main thread, on some win 2000 systems the threads are properly terminated but the associated handles are not freed - this leads to a "handle leak" after a certain time (48 hours). If the threads are started with invokeLater out from the main thread, then the handles are freed properly when the thread terminates.
    Does anybody know how these facts can be put together to get a bigger whole ?
    Thanks a lot.
    Stephan Gloor
    Switzerland

    hi,
    the rule is:
    swing components are not thread-safe except some, and therefore they should only be changed from within the event dispatch thread. this can be accomplished using the methods invokeLater(Runnable) and invokeAndWait(Runnable) in class javax.swing.SwingUtilities.
    best regards, Michael

  • In this case, can I modify swing GUI out of swing thread?

    I know the Swing single thread rule and design (Swing is not thread safe).
    For time-consuming task, we are using other thread to do the task and
    we use SwingUtilities.invokeAndWait() or SwingUtilities.invokeLater (or SwingWorker) to update Swing GUI.
    My problem is, my time-consuming task is related to Swing GUI stuff
    (like set expanded state of a huge tree, walk through entire tree... etc), not the classic DB task.
    So my time-consuming Swing task must executed on Swing thread, but it will block the GUI responsivity.
    I solve this problem by show up a modal waiting dialog to ask user to wait and
    also allow user to cancel the task.
    Then I create an other thread (no event-dispatch thread) to do my Swing time-consuming tasks.
    Since the modal dialog (do nothing just allow user to cancel) is a thread spawn by
    Swing event-dispatch thread and block the Swing dispatch-thread until dialog close.
    So my thread can modify Swing GUI stuff safely since there are no any concurrent access problem.
    In this case, I broke the Swing's suggestion, modify Swing stuff out of Swing event-dispatch thread.
    But as I said, there are no concurrent access, so I am safe.
    Am I right? Are you agree? Do you have other better idea?
    Thanks for your help.

    If you drag your modal dialog around in front of the background UI, then there is concurrent access: paint requests in your main window as the foreground window moves around.

  • Are methods in the Graphics class Thread Safe

    Can methods from the Graphics class (.e.g. drawImage(), drawString(), ect..) be called from any thread? In other words, can two threads that refer to the same Graphics object step on each other methods calls?
    TIA,
    DB
    Edited by: Darth_Bane on Apr 27, 2009 1:44 PM

    No,
    They are GUI activities so you should call them from the Swing Thread ( Event Disptach Thread)
    Now for the JComponent the following are thread safe:
    repaint(), revalidate, invalidate which can be called from any thread.
    Also the listener list can be modified from any thread addListenerXX or removeListenerXX where XX is ListenerType
    Regards,
    Alan Mehio
    London, UK

  • Thread-safe increment()

    class Counter {
    int count = 0;
    int increment() {
    int n=count;
    count = n + 1;
    return n;
    Can you make it thread-safe?

    I need a good book for this topics
    Core Libraries
    I/O
    JavaBeans
    Language and Utilities
    Math     Integration Libraries
    JDBC
    JNDI
    RMI
    Java Language
    Data Types
    Expressions
    Objects
    Syntax     Media Programming
    Image I/O
    Java 2D
    Print Service
    Support Libraries
    Internationalization
    Java Management Extensions (JMX)
    Networking
    Security
    XML     Tools
    Annotation Processing
    Compiler
    Deployment
    Java Platform Debugger Architecture (JPDA)
    Javadoc
    User Interface Libraries
    Abstract Window Toolkit
    Accessibility
    Drag-and-Drop Data Transfer
    Input Method Framework
    Swing     Virtual Machine
    Byte Codes
    Hot Spot
    Memory Management
    Thread Management

  • Repaint() is not thread-safe?

    I saw a description that says repaint() is thread-safe in an old swing tutorial, but not in the current tutorial and its javadoc. So can I assume repaint() is not thread-safe and I should call it from EDT? ... Or if they are thread-safe, why does Sun not document it?

    repaint() calls paint() on EDT... but it calculates dirty region on the current thread and does not get AWTTreeLock.I don't think so.
    repaint() is a java.awt.Component method and doesn't know about Swing's RepaintManager and dirty regions. There may be somthing similar at the AWT level that escaped me, but looking at the JDK1.6 source code, java.awt.Component.repaint() just repaints the whole component.
    Now repaint(long, int, int, int, int) has two versions.
    At the AWT level, it just posts a paint event for the specified region. No race condition, and no risk that he region be wrong, but possibility to invoke multiple paint(Graphics) that overlap, that is, to paint several times the same area - it may be an optimization problem, but it doesn't jeopardize the consistency of the drawing.
    At the Swing level, it does compute dirty regions. In Repaint manageer, the call to extendDirtyRegion(...) is protected within a synchronized block, but the code before that is not. From a quick look, that code is:
    1) walking up the component hierarchy to find the root, which may not be thread-safe, but a well-behaved application shouldn't change the hierarchy from outside the EDT.
    2) walking up a chain of "delegate" RepaintManager, which I knew nothing about... Apparently it's a sun's implementation specific construct, each JComponent can be assigne d a delegate RepaintManager. Again I would claim that such things should not happen outside of the EDT, but I haven't found documentation about this.
    Edited by: jduprez on Jul 20, 2009 2:37 PM
    so no, technically, I can't prove repaint(long, int,int,int,int) is thread-safe.
    But a well-behaved application that updates its widgets on the EDT shouldn't worry (that is, repaint(...) calls can still be invoked outside of the EDT).
    Edited by: jduprez on Jul 21, 2009 7:04 PM - typos

  • SwingWorker process(List V chunks) but List isn't thread safe is it.

    Folks,
    Am I missing something or does
    protected void process(List<V> chunks)in the new 1.6 javax.swing.SwingWorker represent a potential threading issue?
    List isn't thread safe... so why not use a Vector, which is? Except that Vector is currently considered persona-non-grata by bigger brains than me.
    Hmmm... Of course, I don't know which implementation of List is being used under the hood, so I suppose I just have to trust the Java Gods who built the new SwingWorker to have used a thread safe implementation... which is pretty good bet, I suppose...
    Can anyone state categorically that it isn't a problem?
    Thanx. Keith.
    Message was edited by: corlettk PS: I'm knee deep in thread gruel and going down fast.

    publish definitely does not block until process is finished.
    In fact calling publish does not necessarily mean that process will be called right away.
    From the API:
    Because the process method is invoked asynchronously on the Event Dispatch Thread multiple invocations to the publish method might occur before the process method is executed. For performance purposes all these invocations are coalesced into one invocation with concatenated arguments.
    For example:
    publish("1");
    publish("2", "3");
    publish("4", "5", "6");
    might result in:
    process("1", "2", "3", "4", "5", "6")
    Edit:
    The only source I could find for AccumulativeRunnable (the class used to accumulate the arguments passed to publish) was here:
    http://fisheye5.cenqua.com/browse/swingworker/src/java/org/jdesktop/swingworker/AccumulativeRunnable.java?r=1.2
    which isn't necessarily the implementation in the JDK but it's probably close.
    That shows that before process is called the accumulating list reference is nulled, meaning that there is no way that publish can append to the list during a call to process.
    In fact calling publish as the same time as process is executing on the EDT appends the published arguments to a fresh list, leading to another call to process at some later time (in SwingWorker the delay between a call to publish and a call to process is at most 1000/30 milliseconds).
    Message was edited by:
    dwg

  • How does deadlocking happen when not updating UI on swing thread?

    It looks like the 2 objects that cause the deadlock are the RepaintManager and the JComponent.LOCK object...but I can't really find a scenario where this happens in the code.
    Can anybody shed some light on this?

    Basic rule of thumb:
    If you can't guarantee that your code will run on the AWT-Event thread then wrap your calls in a SwingUtilities.invokeLater() call (or its cousin invokeAndWait()).
    Basically this looks like:
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    // put your gui updating code here
    There are two ways to make something thread safe:
    1) Guarantee calls will always come from the same thread
    2) Synchronized shared objects.
    Swing chose choice 1 since choice 2 would be two big of a performance hit. The thread it uses is the AWT-Event thread. The invokeLater call tosses your Runnable object at the end of the Event Queue. The AWT-Event thread pops a Runnable off the Event Queue processes it and then repeats.
    As to specifically whats happening, I can't say without more information. Really you should go back and make sure all your Swing calls are on the AWT-Event thread. That should solve your current problem and prevent future problems.

  • Swing thread race

    Hi,
    I have a problem with the JTree. I have implemented a model for a sort of filesystem, viewable by a JTree. When I click to expand the tree, it seems like the AWT thread block while waiting for the tree node to report its children. Inside the node implementation, I get an error that causes the invokation of a JOptionPane, which in turn causes the gui to crash. I suppose it's because the application tries to show a dialog while the gui thread is busy?
    How can I work this out...?
    BR,
    Michael

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

Maybe you are looking for

  • Video issues in mac os 10.6.4 and windows 7 64x

    To start with, my computer is the late 2008 model Imac, has 3g of memory, and wasn't experiencing any video problems until earlier this month. I've already had it serviced, and was told that the issue was resolved, and was unrelated to hardware. Fift

  • How to update XML Facts in rule author

    Hi, since there is not a separate forum for the rules engine and this is tightly related to BPEL, so I thought I'd post the question here. what's the process to update XML Facts in the rule author and the BPEL process that is already using the rule r

  • Problem w. transaction notSupported / releasing JDBC connections

              We are making a call from our EJB client to a stateless session EJB (1) with transaction attribute 'Required' for all methods. From this EJB (1) we get a JDBC connection from the pool and do some JDBC calls (no updates). We then make a call

  • Macbook + Alesis iO26 + HP 20" TFT = bad inteference

    Hi people So I'm using a Intel Macbook 2gig core 2 duo with an Alesis iO26 firewire audio interface. These two work great together but when I plug in my newly acquired HP 2007 20" TFT (vga only) I get serious sonic interference. I've tried two Apple

  • WCF Web Service Support

    Does Xcelsius support Microsoft Windows Communication Foundation Web Services? I've downloaded the trail version of Xcelsius Engage 2008 and when I try to load a WCF WSDL I get an error message stating Unable to Load. Thanks in advance,