AWT on the Event Dispatch Thread?

Last night I was teaching my Intro Java class about Swing windows, and specifically discussing the event dispatch thread. I dutifully warned everyone that all creation and update of Swing components had to happen on this thread, usually by calling SwingUtilties.invokeLater(). Then one of my students asked a question that stumped me:

Is the same true for AWT components?

It certainly seems logical that this be the case. However, I don’t ever remember anyone ever saying this. Googling didn’t find anything that squarely addressed this question. All the information I found about SwingUtilties.invokeLater() and related subjects seemed to focus very specifically on Swing, not the AWT. The single exception was this Wikipedia article but I’m not sure I can trust that on such a fine technical point. Does anyone happen to know the answer to this question for sure? If the answer is no, the AWT components don’t need to use SwingUtilties.invokeLater() or equivalent, I’d also be curious why they don’t compared to Swing components which do. Is there an AWT expert in the house?

3 Responses to “AWT on the Event Dispatch Thread?”

  1. John Cowan Says:

    Absolutely yes.

    See the JavaDoc for java.awt.EventQueue, notably the methods invokeLater and isDispatchThread. There is a single dispatch thread for each EventQueue, and there is normally only one of those (retrieved by the static method Toolkit.getSystemEventQueue), although the documentation notes that browsers are free to run separate applets in different contexts, implying multiple EventQueues, each with their own dispatch thread.

    Swing essentially inherits all this machinery from AWT. The purpose of it is to avoid having to do expensive and tricky fine-grained locking to prevent the screen from being updated in inconsistent ways.

  2. Erik Tribou Says:

    The AWT components were designed to be thread safe, but in reality they weren’t (which is why there is no attempt to make swing components thread safe, except in a few specific circumstances involving the document of text components). It’s best to only access them from the event thread.

  3. Andrew Thompson Says:

    I can tell you from long, personal experience that AWT components *do* need to do invokeLater(). Also, if you look at the SwingUtilities.invokeLater() I it just calls EventQueue.invokeLater() internally :)

    I believe once found an acknowledgment from Sun that the AWT is not thread safe, I think in the release notes or a related file from JDK 1.2, but I can’t find it now.

Leave a Reply