Event Dispatching Thread - Executing Code in The EDT

Executing Code in The EDT

Other application threads can have code executed in the event dispatching thread by defining the code in a Runnable object and pass it to the SwingUtilities helper class or to the EventQueue. Two methods of these classes allow:

  • synchronous code execution (SwingUtilities.invokeAndWait(Runnable) or EventQueue.invokeAndWait(Runnable))
  • and asynchronous code execution (SwingUtilities.invokeLater(Runnable) or EventQueue.invokeLater(Runnable))

from the EDT.

The method invokeAndWait should never be called from the event dispatching thread—it will throw an exception. The method SwingUtilities.isEventDispatchThread or EventQueue.isDispatchThread can be called to determine if the current thread is the event dispatching thread.

Another solution for executing code in the EDT is using the worker design pattern. The SwingWorker class, developed by Sun Microsystems, is an implementation of the worker design pattern, and as of Java 6 is part of standard Swing distribution. The open source project Foxtrot provides another synchronous execution solution similar to SwingWorker.

Read more about this topic:  Event Dispatching Thread

Famous quotes containing the words executing and/or code:

    Executives are like joggers. If you stop a jogger, he goes on running on the spot. If you drag an executive away from his business, he goes on running on the spot, pawing the ground, talking business. He never stops hurtling onwards, making decisions and executing them.
    Jean Baudrillard (b. 1929)

    Hollywood keeps before its child audiences a string of glorified young heroes, everyone of whom is an unhesitating and violent Anarchist. His one answer to everything that annoys him or disparages his country or his parents or his young lady or his personal code of manly conduct is to give the offender a “sock” in the jaw.... My observation leads me to believe that it is not the virtuous people who are good at socking jaws.
    George Bernard Shaw (1856–1950)