1

I came across the following piece of code in my code base and I dont understand how it works.I'm a bit of a novice at Swing, hence sorry if it seems like a silly question.

public static void invokeOnEventDispatchThread(Runnable r){
try{
  if(SwingUtilities.isEventDispatchThread()){
    r.run();
  }else{
    SwingUtilities.invokeAndWait(r);
  }
}catch(Exception e){
  ;
}

}

Here will r.run() be invoked immediately in the event dispatch thread? Is the point of the method that r.run() be called asap, moving it to the head of the queue?

Thanks.

Poornima Prakash
  • 320
  • 5
  • 15

1 Answers1

1

The point of the method is to run the code synchronously:

  • either you already are executing in the EDT and the code is simply run
  • or you aren't and the method will wait until the runnable has been executed by the EDT

In particular, the javadoc for invokeAndWait states that the method should not be called on the EDT hence the 2 branches in your code.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thanks for replying. "either you already are executing in the EDT and the code is simply run" - Is the code simply run immediately? or is it put in the event queue and run when its turn comes? – Poornima Prakash Dec 07 '12 at 11:35
  • `r.run()` always runs immediately in the current thread, whether it is the EDT or not does not make a difference. So yes it runs immediately and no it is not put in the queue. The queue is there for non-EDT threads only. – assylias Dec 07 '12 at 11:38