Is it safe to use SwingUtilities.invokeLater(), while updating GUI?

Hi,
I am updating GUI components in synchronized block which is runinng on main() thread my application hangs, but if I use SwingUtilities.invokeLater(...) then it runs fine.
My question is:
Is it safe to use SwingUtilities.invokeLater(...) in synchronized block.
Edited by: Amol_Parekh on Nov 1, 2007 1:28 AM

Paul Hyde in his "Java Thread Programming" (great book!!!) says it is.
With invokeLater() you say to the Thread Scheduler you want that code to run on the Swing thread. In fact, if that is the only thing you do in the synchronized block I think it is unnecessary.
Greetings,
astrognom

Similar Messages

  • Why do we have to use SwingUtilities.invokeLater() to update UI status?

    I just don't understand very well why we have to use SwingUtilities.invokeLater() to update UI status. Why not just new a thread in actionPerformed() method and do time consuming tasks in this thread and update UI status in it? Some tutorials say it is not safe to update UI status not in Event Dispatch Thread, I don't understand, why is it not safe? Can anyone provide a scenario for this? I just write an example, a button and a progressbar, click button, progressbar keeps updating value. I just create a new thread to do this, don't find any issue. Thanks.

    [Swing single threaded rule|http://www.lmgtfy.com/?q=swing+single+threaded+rule]
    db

  • Should I use a SwingWorker or SwingUtilities.invokeLater() to update my UI?

    Are there specific situations where you want to use method above the other? This whole swing concurrency is very new to me, and I don't really know where to begin.

    When executing long running code you don't want the GUI to freeze. Therefore you have two things to be concerned about. First, you want the long running task to execute in a separate Thread. Secondly, when you need to update the GUI from this code you need to make sure the code executes on the Event Dispatch Thread (EDT).
    You can code this manually by creating a separate Thread and then use SwingUtilities.invokeLater() when necessary.
    A SwingWorker tries to simplify this process by having a simple API where you can add code that executes on a separate Thread or where you can add code that executes on the EDT.
    So in the case of managing long running tasks, the end result should be the same.
    Hwever, there are times when I know code is already executing on the EDT, but I sometimes use invokeLater(..) to force my code to the end of the EDT. This is used in special situations when code doesn't execute in the order you want.
    For example, I've tried to add a FocusListener to a JFormattedTextField to "select the text" when it gains focus. The problem is the the UI also adds a FocusListener. Because of the way listeners are handled the last listener added to the component executes first. Therefore, using the invokeLater() forces my listener code to execute last.
    You can try this code to see what I mean:
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
         .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
         public void propertyChange(final PropertyChangeEvent e)
              if (e.getNewValue() instanceof JTextField)
                   //  invokeLater needed for JFormattedTextField
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             JTextField textField = (JTextField)e.getNewValue();
                             textField.selectAll();
    });Edited by: camickr on Mar 5, 2011 2:36 PM

  • Is It Safe To Use Macbook Pro While Charging?

    Is it safe to use your macbook while charging or it will make you battery broken.answers please. thank you.

    angelopaolo wrote:
    Is it safe to use your macbook while charging or it will make you battery broken.answers please. thank you.
    Of course it is ok.

  • EJB function using  SwingUtilities.invokeLater()  is problm msg publishing

    My problem for JMS using Message publish to group of people , What I did, Server side I am pushing message for each topic , (it could be n number of topic ) I created for Every five topic to as single thread. (Topic will be [ 200 ~2000] ) ,
    Some time this SwingUtilities.invokeLater() function will shown error Message AWT event
    I am using EJB Method for like this.
    new Thread()
    public void run()
         SwingUtilities.invokeLater( new Runnable() {
    public void run() {
         HashMap map=null;
         try
              map=MessagePublish2Group.init(); // to getting connection function .
              InitialContext iniCtx=(InitialContext)map.get("InitialContext");                
                   TopicSession session =(TopicSession) map.get("TopicSession");
                   TextMessage txtmsg = session.createTextMessage();
                   txtmsg.setText(Message);
              for(int i=0;i<userlist.length;i++)
                   try
                   Topic     receiver =(Topic) iniCtx.lookup("topic/"+userlist[i]+"");
              TopicPublisher usertopic = session.createPublisher(receiver);
              usertopic.publish(txtmsg);
              usertopic.close();     
                   catch(Exception gexp)
              close(map); // // to closing connection function .
         catch(Exception exp)
              close(map); // to closing connection function .
    exp.printStackTrace();
    }.start();
    Thanks in advance
    Sasikumar (Sasimsit)

    {color:red}{size:20px}TRIPLE POSTED{size}{color}
    [http://forums.sun.com/thread.jspa?threadID=5333442]
    [http://forums.sun.com/thread.jspa?threadID=5333443]
    [http://forums.sun.com/thread.jspa?threadID=5333445]
    Cross posting is rude.
    db

  • Using Dynamic actions while updating a Transfer action

    Hi all,
        I am trying to run a Transfer action, (80), which updates the Infotype 0000 and Infotype 0001. When the entry in the Infotype 0001 is saved, a dynamic action is triggered and a custom infotype is updated automatically. I need to find a FM that takes care of any dynamic actins associated to an Infotype.
       I tried using a BDC, but it was not successful. While using the FM HR_INFOTYPE_OPERATION, I somehow am not able to store the data into the Infotypes, leave alone the dynamic action. Can someone please suggest a solution.
    Thanks,
    Amar

    Hi VK,
        The dynamic action is:
         06     993     F     GET_DU(ZHRDUDYNCALL)
         06     994     I     COP,9009,,,(P0001-BEGDA),(P0001-ENDDA)/D
         06     995     C     ----P9009-SEQNR=P0001-SEQNR ---***
         06     996     W     P9009-AEDTM=P0001-AEDTM
         06     997     W     P9009-UNAME=P0001-UNAME
         06     998     W     P9009-DU_CD=RP50D-FIELD1
         06     999     C     --END OF ENTRY IN TABLE PA9009--
         08     891     C     --CREATE ENTRY IN TABLE PA9009----
         08     892     P     SY-DATUM=SY-DATUM
         08     893     C     GET_DU(ZHRDUDYNCALL)
         08     894     I     DEL,9009,,,(P0001-BEGDA),(P0001-ENDDA)/D
         08     895     C     P9009-DU_CD=RP50D-FIELD1
         08     896     C     --END OF ENTRY IN TABLE PA9009--
    Thanks,
    Amar
    Edited by: Amarpreet Singh Reen on May 4, 2009 3:54 PM

  • Is it safe to use iPod while it's charging?

    Just wondering if it's safe to use the iPod while it's charging with an adapter?

    Not only is it safe, using it when charging prevents using up the battery. The battery has a finite number of charge/discharge cycles...

  • Why do we have to call SwingUtilities.invokeLater()??

    Hello,
    i am not understanding the concept of SwingUtilities.invokeLater() i read the documentation but still couln't get why it is needed and when it is needed?do we have to call this function everytime some event is generated and some action is performed on component Ex.mouse click on button etc?? Please give me little details regarding it's concept!
    Thanks in advance :)

    (guys correct me if i'm wrong here)Most of the time that's correct, but for some customizations it is necessary to run custom code after all default code contained in the Swing classes has been executed. For example, to request focus be given to a component that would otherwise not be immediately focused, if you omit to enclose that in a invokeLater, it will get the focus but immediately lose it as still-queued events mandate the transfer of focus elsewhere. Moreover, as the event delivery mechanism is asynchronous, the behavior may be inconsistent.
    In general, any customization that may conflict with the normal flow should be wrapped in invokeLater, whether run from the EDT or another thread. The exceptions here are methods which the API declares to be thread safe.
    what you want to do is run that time consuming process in a thread, and when you need to call back to update the GUI, then use SwingUtilities.invokeLater.Or use SwingWorker, that's what it's for.
    cheers, db

  • Error while updating time sheet with BAPI_CATIMESHEETMGR_INSERT

    Hi Gurus,
    We are uploading data from 3rd party software to SAP with Z program.
    In this Z program using BAPI_CATIMESHEETMGR_INSERT.
    While updating data manually with CAT2 or with BAPI, data is entered properly without any problem but while using the bapi in Z program  error message " Version 0 is not set up for controlling area" is coming .
    Hence Version 0 is already active for the controlling area for fiscal year 2010.
    Please help me to resolve the issue.
    Thanks,
    Neha Duseja

    - First - Try to accomplish this via transaction CAT2 (*) (and then CATA or CAT6 to upload data to HR) - You may require some Customizing here ([Entry of Attendances and Absences for HR Time Management|http://help.sap.com/saphelp_bw/helpdata/en/64/400456470211d189720000e8322d00/frameset.htm])
    - Then - Use the same values in  [BAPI_CATIMESHEETMGR_INSERT|http://www.sdn.sap.com/irj/scn/advancedsearch?query=bapi_catimesheetmgr_insert#sdn_content_category_value_wiki]
    Regards,
    Raymond
    (*) Or ask to your functional

  • Fatal error while updating to 10.2

    Hi,
    I got a brand new Q5 - no apps other than default and there is plenty of memory available (more than the software update size). I am trying to update the device software using BBLink. While updating, it gives me an error "Fatal Unrecoverable error".
    I also can't seem to setup the Blutooth device connection between my Q5 and my desktop.
    Any help is highly appreciated.

    Hi and Welcome to the Community!
    Given the error you receive, I would first check to be sure you have the most recent version of LINK. Failing that, I would attempt to use the Sachesi method of updating. Failing that as well, I would revert to using an AutoLoader to see if it can accomplish what LINK cannot do. Do be aware that an AutoLoaders are completely destructive to your device data...be sure you have a full backup as well as full manual documentation of your configuration.
    Good luck!
    Occam's Razor nearly always applies when troubleshooting technology issues!
    If anyone has been helpful to you, please show your appreciation by clicking the button inside of their post. Please click here and read, along with the threads to which it links, for helpful information to guide you as you proceed. I always recommend that you treat your BlackBerry like any other computing device, including using a regular backup schedule...click here for an article with instructions.
    Join our BBM Channels
    BSCF General Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • CIN - MRP Indicator while updating excise duties

    While updating excise duties befor posting excise invoice... if we use MRP indicator while updating bed, aed, sed etc...then what is the impact of it.....in further process and how we can move smoothly....
    Thanks in Advance,
    Navin

    Hai ,
    MRP indicator is used in the case of procurement of materials from Trader or dealer with inclusive of excise duties in the Net price itself. We can enter the excise duties manually in the J1iex by flag the MRP indicator so that we can avail the cenvat credit for this material.

  • Anyone use MSI LiveUpdate2 to update MSI GFX card bios?

    I using MSI GF4 Ti4200 64MB.
    My BIOS version is 4.25.00.29.10
    Anyone has newer bios than me?
    Izzit safe to use the LU2 to update my gfx bios?
    MSI GF4 cards have dual bios right?

    looking for problems ? do you need that update ?
    or you want to do it cuz may be someone has newer ?  

  • Is is safe to use a TENS unit while working on my iMac?

    I use a TENS unit for back pain. Since it discharges electrical currents, I'm wondering if it's safe to use it while I'm on the computer. Thanks.

    I have little or no knowledge on this subject but I see no one else is answering so...
    Have you considered one of the downloadable VNC apps, such as "Chicken of the VNC"? There are others also.

  • Is it safe to use the new ipad (3rd gen) while on charge

    I have the New Ipad (3rd Gen) 32gb wifi onlymodel,, and I use it while on charge i notice that it took way longer to charge while i use... will in not damage the devoce nor the batter if i use it while on charge?

    The quickest way (and really the only way) to charge your iPad is with the included 10W USB Power Adapter. iPad will also charge, although more slowly, when attached to a computer with a high-power USB port (many recent Mac computers) or with an iPhone Power Adapter (5W). When attached to a computer via a standard USB port (most PCs or older Mac computers) iPad will charge very slowly (but iPad indicates not charging). Make sure your computer is on while charging iPad via USB. If iPad is connected to a computer that’s turned off or is in sleep or standby mode, the iPad battery will continue to drain.
    Apple recommends that once a month you let the iPad fully discharge & then recharge to 100%.
    How to Calibrate Your Mac, iPhone, or iPad Battery
    http://www.macblend.com/how-to-calibrate-your-mac-iphone-or-ipad-battery/
    At this link http://www.tomshardware.com/reviews/galaxy-tab-android-tablet,3014-11.html , tests show that the iPad 2 battery (25 watt-hours) will charge to 90% in 3 hours 1 minute. It will charge to 100% in 4 hours 2 minutes. The new iPad has a larger capacity battery (42 watt-hours), so using the 10W charger will obviously take longer. If you are using your iPad while charging, it will take even longer. It's best to turn your new iPad OFF and charge over night. Also look at The iPad's charging challenge explained http://www.macworld.com/article/1150356/ipadcharging.html
    Also, if you have a 3rd generation iPad, look at
    Apple: iPad Battery Nothing to Get Charged Up About
    http://allthingsd.com/20120327/apple-ipad-battery-nothing-to-get-charged-up-abou t/
    Apple Explains New iPad's Continued Charging Beyond 100% Battery Level
    http://www.macrumors.com/2012/03/27/apple-explains-new-ipads-continued-charging- beyond-100-battery-level/
    New iPad Takes Much Longer to Charge Than iPad 2
    http://www.iphonehacks.com/2012/03/new-ipad-takes-much-longer-to-charge-than-ipa d-2.html
    Apple Batteries - iPad http://www.apple.com/batteries/ipad.html
    Extend iPad Battery Life (Look at pjl123 comment)
    https://discussions.apple.com/thread/3921324?tstart=30
    New iPad Slow to Recharge, Barely Charges During Use
    http://www.pcworld.com/article/252326/new_ipad_slow_to_recharge_barely_charges_d uring_use.html
    Tips About Charging for New iPad 3
    http://goodscool-electronics.blogspot.com/2012/04/tips-about-charging-for-new-ip ad-3.html
    Prolong battery lifespan for iPad / iPad 2 / iPad 3: charging tips
    http://thehowto.wikidot.com/prolong-battery-lifespan-for-ipad
    iPhone, iPod, Using the iPad Charger
    http://support.apple.com/kb/HT4327
    Install and use Battery Doctor HD
    http://itunes.apple.com/tw/app/battery-doctor-hd/id459702901?mt=8
    In rare instances when using the Camera Connection Kit, you may notice that iPad does not charge after using the Camera Connection Kit. Disconnecting and reconnecting the iPad from the charger will resolve this issue.
     Cheers, Tom

  • Question on SwingUtilities.invokeLater

    The program I have included is attempting to "simulate" opening and loading a file into memory.
    Run the program, select File and then select Open. You will notice that the File menu does not disappear for 3 seconds (i.e. until the file has been completely read).
    I was hoping it was possible to close the File menu while the file is being read. While reading through various documentation on the invokeLater() method I found the following:
    "Both invokeLater() and invokeAndWait() wait until all pending AWT events finish before they execute"
    Therefore by adding an invokeLater() method I was hoping to accomplish the following series of events:
    1) click on Open menuItem
    2) invoke OpenAction
    3) do the "repaint" (which would cause the file menu to disappear)
    4) finish the OpenAction
    5) do the long running task
    Hopefully you understand what I am trying to accomplish and can provide some guidance. Here is the sample program:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestInvokeLater extends JFrame
         JFrame frame;
         JMenuBar menuBar;
         JMenu menu;
         JMenuItem menuItem;
         public TestInvokeLater()
              frame = this;
              setDefaultCloseOperation( EXIT_ON_CLOSE );
              menuBar = new JMenuBar();
              menu = new JMenu("File");
              menuBar.add(menu);
              menuItem = new JMenuItem( new OpenAction() );
              menu.add(menuItem);
              setJMenuBar( menuBar );
              JPanel panel = new JPanel();
              panel.setPreferredSize( new Dimension( 100, 100 ) );
              setContentPane( panel );
         class OpenAction extends AbstractAction
              public OpenAction()
                   putValue( Action.NAME, "Open" );
              public void actionPerformed(ActionEvent e)
              repaint();
         SwingUtilities.invokeLater(new Runnable()
         public void run()
              try
                   Thread.sleep(3000); // simulate log running task
              catch (Exception e) {}
         public static void main(String[] args)
              JFrame frame = new TestInvokeLater();
              frame.pack();
              frame.show();
    }

    Thanks for the input, but I still have some confusion -
    "invokeLater() simply appends the thread to the end of the dispatch queue, this happens before the event code to hide the file menu gets queued"
    This is the part that confuses me. If I understand event driven programming correctly then the code for the MenuItemClicked must complete execution before the next event in the queue can be executed.
    If we assume the code for MenuItemClicked is something like:
    1) fireActionEvent
    2) fireCloseMenuEvent
    When MenuItemClicked is finished executing the next event in the queue is the ActionEvent which invokes my ActionPerformed code:
    1) I use the Swing invokeLater() method (which means it should be queued "after" the fireCloseMenuEvent
    Does this make any sense?

Maybe you are looking for