javamultithreadingswingevent-dispatch-threadinvokelater

Swing: Running code immediately vs invokeLater


I'm currently working with a thread control class someone else wrote. It is used for a java swing application. I have two methods, but I am confused as to why I am getting different behaviors from both. From what I know and read about the event dispatcher thread and Swing, there should be no difference in the two methods below. Apparently, this is not true.

//If this is the AWT Event Processing thread then run the code immediately, 
//otherwise schedule it for later processing

 public static void runWithEventThread(Runnable r)
{
    if (EventQueue.isDispatchThread())
    {
        r.run();
    }
    else
    {
        EventQueue.invokeLater(r);
    }
}


//Schedule the runnable for later processing by the AWT Event Queue
public static void runLaterWithEventThread(Runnable r)
{
    EventQueue.invokeLater(r);
}

When using runWithEventThread() to display popups while updating GUI (new buttons/repainting), I found that the GUI would mess up sometimes. However when using runLaterWithEventThread(), it was all fine, no issues.

Only problem is that when using runLaterWithEventThread() I found that when I had multiple popups that would be displayed one after the other (after OK clicked) all popups were displayed at once.

From what I understand, both the methods should be doing the same thing. Can someone please explain what is going on


Solution

  • If your first method is executed from the event thread, it MAY act differently than the second method: If there are any events currently waiting on the event thread, those events will be processed BEFORE your run() method is executed if you use the second method, but if you use the first method, your run() method will be executed immediately, and any existing events on the queue will be run AFTER your run() method finishes.