Debugging Swing EDT Problems
I recently joined a new project, which is all about Swing GUI programing. We had a lot of weired problems that were nondeterministic. The problem was that the Swing components were accessed from multiple threads which may lead to concurrency problems, sadly Swing doesn’t enforce you neither help you to prevent this mistake.
Always remember the following rule when working with swing: Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread. This rule means that every access to a swing component should occur on the Event Dispatch Thread (EDT) as soon as the component has been realized.
I was thinking of an automatic way to detect this problem in the existing source, because i have better things to do than searching for swing threading issues in more than 1000 Java files. During my research i found an interesting approach from Scott Delap. The main idea is to hook into the swing repaint request by writing a RepaintManager that checks if the call was done from the EDT. This check can be done easily with following statement: SwingUtilities.isEventDispatchThread(). You could also call EventQueue.isDispatchThread() directly to avoid one indirection as SwingUtilities.isEventDispathThread() does nothing more as just calling the corresponding EventQueue method. A working implementation to find EDT bugs can be found at the SwingHelper page. Sadly this only works for Java 1.5 and above, so I had to do some rewriting to get it working with a Java 1.4 VM (the source can be downloaded here).
This approach to find EDT bugs worked great for us, we found about 100+ violations in just a second. Sadly fixing them took a little bit longer ![]()
Please note that this approach does not find all EDT problems as not all methods from Swing cause a repaint event. Getters from Swing components are such an example.
If you would like to have a more complete solution you may be interested in this blog entry from Alexander Potochkin.
Add comment October 29th, 2007