Home / Java Patterns and Pitfalls     frequal.com

Debugging Swing Event Dispatch Thread Violations

Detection

Through the hard work of Scott Delap and Alexander Potochkin it is now easy to find many Swing threading problems caused by making Swing calls from a thread other than the Event Dispatch Thread (EDT).

These are the three easy steps:

The resulting output on stdout will include stack traces of each call to an EDT-only method from a non-EDT thread.

Fixing

Using SwingUtilities.invokeAndWait() but make sure you're not already on the EDT first. This method won't return until the Runnable you've passed to it is complete. This means you can safely assume that the Runnable is complete on later lines in the code.

Alternatively, you can use SwingUtilities.invokeLater(). This will let the invoking thread continue to do other things. If the Runnable and the invoking thread are doing unrelated tasks in parallel, this is a good thing. However, if you later try to use the objects being used in the Runnable the access should be synchronized to ensure the EDT and your thread don't conflict.


Last modified on 31 Aug 2009 by AO

Copyright © 2024 Andrew Oliver