Skip to main content

Re: Swing versus SWT Thread Confinement

Posted by robogeek on April 25, 2007 at 2:33 PM PDT

In Swing versus SWT Thread Confinement is offered a suggestion to make Swing take a behavioral leaf from SWT, and to change Swing so that it "fails fast" when called from a thread other than the event dispatch thread. Since Swing (and SWT) are not multithread safe, if you call Swing methods from outside the event dispatch thread the behavior is "undefined". This is a nice way of saying you're on your own, that your program might work, or it might die in flames, or it might just run weirdly with random behavior. And, I think, some of the frustration over Swing applications might stem from those who call Swing methods from outside the event dispatch thread, which then will have undeterminable behavior.

The simple implementation would be to edit every Swing method inserting checks to see if the caller is not on the EDT and to throw an IllegalStateException.

Until recently I was part of the CCC, an internal committee where we review Java SE changes to look for compatibility and conformance issues. It's very peculiar work reviewing API or other interface changes and trying to imagine how likely it is the change will or will not break applications. What I got from sitting in that group for those 3 years is an enhanced appreciation for maintaining compatibility. Sometimes in the CCC we would preserve some existing behavior, even if it was known to be buggy or a poor choice of behavior, so that we would not break existing applications in the field.

Clearly while it's a poor choice that applications can call Swing methods from outside the EDT, clearly there are applications who do that. And the simple version of the change, to throw exceptions for that case, would break existing applications in the field.

A preferable route is to come up with a way to make the check optional. I agree the check is a good idea, and to be able to set a flag that turns this check on an application author could then run their application with the checking mode enabled and find out when/where their application calls Swing from outside the EDT.

The more serious proposal.. to add an annotation to Swing methods saying they require being run on the EDT, that's a good idea. And I am envisioning it's possible to write a code munger using the Jackpot engine in Netbeans 6 so that it searches for methods having that annotation, and inserts or deletes the checking code.

Related Topics >>