Is component creation off EDT really a bug?
At JavaOne I had some discussions with NetBeans Platform users, whether the way the UI is created in NetBeans is OK or not. The topic came up again when I tried to use substance 5.2 as the LAF for NetBeans. Substance throws an exception when it finds components that are created outside the EDT, while NetBeans does this quite extensively and also intentionally. Obviously, when you create a very large and modular UI, component creation off the EDT is something rather useful. But the rules seem to have changed at one point in time, and if it’s to be considered a bug now, it would have to be discussed if it can be fixed. Everything pointed to that direction and it seemed quite clear, but after I had some discussions with Wade from the Dream Team and later investigated further how this new rule entered the world of Swing, I’m not so sure anymore. So: Let’s get this sorted!
Swing documentation is lacking a clear statement if component creation off the EDT is to be considered a bug. In the beginning the official statement was:
“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.”
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
So component creation off the EDT was officially considered OK. Only when the component is realized, you had to make sure to only access it from EDT. At one point all the Swing examples were changed to also do component creation on the EDT. Obviously because one of the examples had issues:
“Out of all the demos in the Swing Tutorial, we encountered a problem only in ComponentEventDemo. In that case, sometimes when you launched the demo, it would not come up because it would deadlock when updating the text area if the text area had not yet been realized, while other times it would come up without incident.”
http://web.archive.org/web/20040413005634/http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
I don’t have the old ComponentEventDemo lying around, so I can’t check, but it would be interesting to see what the actual problem was… The above link is not an official document, but sits somewhere in the archives. Still now it’s recommended in the Swing tutorial to create components in EDT:
“Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread. This restriction is discussed further in the next section. ” ( bold text formatting by me. by the way, there is not really a discussion in the next section )
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/initial.html
And also in the API Doc the example does that:
http://java.sun.com/javase/6/docs/api/javax/swing/package-summary.html#threading
While these statements are recommendations in my eyes, In the meantime this has widely been interpreted as an official statement by sun with the effect, that most Swing developers consider component creation outside EDT as a bug. There’s a huge difference between a recommendation to avoid threading issues and a bug. But today this is even a question asked in Job interviews. And there are tools helping to find this bug. There are even popular libraries, like Substance Look & Feel enforcing component creation on EDT by throwing Exceptions otherwise:
http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html
http://www.javaworld.com/javaworld/jw-08-2007/jw-08-swingthreading.html?page=5
http://www.pushing-pixels.org/?p=368
Also people inside the Swing team seem to have adopted this thought, and officially close bugs with this explanation:
“This is not expected to work since about 2003. The rules for threading in Swing were changed to say that all object contruction must be done on the event dispatching thread (EDT). Prior to then object contruction was allowed before the top level(Frame) was realised, but that is no longer the case. Almost all code in Swing assumes it is running on the EDT in a single threaded model, Nimbus LAF is no different. There is documented in the Swing Tutorial at http://java.sun.com/docs/books/tutorial/uiswing/concurrency/initial.html .Also the history is exmplained at http://bitguru.wordpress.com/2007/03/21/will-the-real-swing-single-threading-rule-please-stand-up/”
http://bugs.sun.com/view_bug.do?bug_id=6718641
Now: is it a bad practice or a bug? We need a clear official statement if component creation off the EDT is a bug or not. Large swing projects like NetBeans are using component creation off the EDT extensively and it would cost a lot of effort to change this:
http://www.netbeans.org/issues/show_bug.cgi?id=168779
So Swing team, what’s the answer to this? Once and for all: Let’s get this sorted!
Update: I had a ( very lively
) discussion with Jonathan Giles on his blog, who has linked to this article, and Josh Marinacci, former member of the Swing Team has commented:
“As a former member of the Swing Team I’m going to go ahead and say that creating UI objects (not just components) off of the EDT is a bug in your program.
Until the 1.4/1.5 timeframe we said it was okay to create your UI objects off of the EDT in certain cases (main frame not initalized). This was our mistake. We should have said this because it depends on particular implementation details of Swing (the order in which things are initialized internally), and it turns out we were wrong in some cases. Therefore we now say that creating or manipulating any UI object off of the EDT is a bug. Doing so will probably work fine in 99% of the cases, but you have now introduced potential race conditions in your app that may give you strange behavior later on.
One more detail, and this is important. As we work to further improve startup time of the VM and the Swing infrastructure, we will likely change the internals of Swing. This may increase the likely hood that code which used to work fine off of the GUI thread will now break. Therefore it is *very* important that you stay on the GUI thread; and that’s why I say: yes, it’s a bug!”
Thanks a lot Josh! Not only did you give a clear answer, but also an explanation as to why It’s a bug and not only a bad practice. I really do appreciate this!



My take: there has been a lack in consistency in the implementation of Swing, so some parts probably are ok, others not. And maybe, some parts that were ok in the past, at a certain point weren’t any longer, after some refactoring. So, it sounds as a matter of chances, and given the randomness of consequences of threading in this are, I think we are much safer if we consider the thing a BUG. I think Kirill is plentifully right in using assertions for that.
Comment by Fabrizio Giudici
— 23. July 2009 @ 12:48
As far as I know, EDT is used for event handling, so I don’t really see why all components MUST be created inside that thread by default… unless “creation” means “initialization”. Even the case, if that initialization doesn´t generate events, I still don´t see so much stressing around “build them inside the EDT”.
I think there is a very different point of view, on this and other subjects, when the opinions come from either library developers or application developers.
Just a brief example: Substance consistently throws an exception of the type “not running inside the EDT”, when you call an UIManager.setLookAndFeel from the initialize method of Swing Application Framework. That method runs inside the EDT. Swing Labs documents it so. In case you doubt, try executing SwingUtilities.isEventDispatchThread() inside the block of that method, and you’ll see it resturns TRUE.
Who’s wrong, Substance or Swing?
After that example of detection inconsistency results, I have the feeling that either there is a terrible mess around Swing development, or the mess comes from someone elses trying to push every development around Swing, into their particular design camps.
I guess there is too much hype around “libraries requirements”, and too little attention to applications ones, as if the last ones would always have to constantly adapt themselves to the “desig goals” of the former ones.
Comment by ch
— 23. July 2009 @ 13:47
If you write Swing applications you may want to consider FEST for functional testing those applications. FEST offers support for detecting EDT violations.
http://fest.easytesting.org/
Comment by Michael Hüttermann
— 23. July 2009 @ 20:50
[...] is a discussion on whether component creation off of the EDT is really a bug. Frankly I didn’t even bother to read the article, as in my humble opinion it’s simple: [...]
Pingback by Java desktop links of the week, July 27 | Jonathan Giles
— 26. July 2009 @ 23:02
IMO it’s not a bug, it’s moreover a specification issue - if you ignore your app can fail.
As Alex from Sun already wrote in the mentioned article (http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html):
‘Initially there was a rule that it is safe to create and use Swing components until they are realized but this rule is not valid any more, and now it is recommended to interact with Swing from EDT only’
So for me this is a clear statement but unfortunately many Swing developers don’t know the rule because AFAIK it’s not part of the official Swing doc.
BTW: I’ve often seen weird things happen by ignoring this rule.
Comment by wzberger
— 27. July 2009 @ 09:25
@Fabrizio: It might be as you say, but with the lack of official information it’s hard to tell. My intention is to get an officialy statement from the Swing team about this. And not only “Yes it’s a bug” or “no it isn’t” but an actual explanation. All the examples I’ve seen so far were examples where the developer has introduced a bug by using component creation in a certain way. The message that I take away from these examples is, that it must be used with care (like threads generally need to be used with care). The info supplied by sun doesn’t clarify anything either. Except of a cryptic sentence in the Swing tutorial pointing to a non existing explanation in the next section, an unofficial document somewhere in the archives pojnting to a problem with one of the Swing examples and a bug closed with a reference to one of the articles there’s nothing (to my knowledge). Since a lot of applications are using component creation off EDT I think it would be important to have an official statement.
Comment by Toni
— 27. July 2009 @ 09:41
@carlos:
>As far as I know, EDT is used for event handling, so I don’t really see why all components MUST be created inside that thread by default… unless “creation” means “initialization”. Even the case, if that initialization doesn´t generate events, I still don´t see so much stressing around “build them inside the EDT”.
Exactly, it used to be officially OK, suddenly it isn’t any more without any explanation, and also there is no official statement fro Sun that it is. This has been decided otside Sun. Maybe it’s a bug maybe it isn’t. I think it needs to be decided. The world will be nicer for Swing developers afterwards
.
Comment by Toni
— 27. July 2009 @ 09:44
@Michael: As far as I know the FEST approach uses a custom RepaintManager which is based on the one by Scott Delap and Alex Potochkin. Do you know if it supports the “complete” flag, that allows to switch the component creation check on and off?
–Toni
P.s.: Ich habe mails von Dir auf der JUG liste gesehen- Bist Du gerade in München?
Comment by Toni
— 27. July 2009 @ 09:51
@Wofgang: I agree with you. I personally think that it should be avoided since it’s errorprone, but it’s not a bug ( Actually I changed my mind in this point after my discussion with Wade
http://forums.netbeans.org/topic15202.html ). I agree that a clear statement with explanations should be part of the Swing Doc.
Comment by Toni
— 27. July 2009 @ 10:01
It’s been a while (about 18 months) since I have written Swing UI code. That used to be pretty much all I did. I tested against Java 1.4, 5 and 6. I saw a lot of bugs related to code that manipulated Swing components *after* they were realized. Inconsistent state (enabled/disabled), bad event handling, components not displaying then displaying, painting bugs, focus bugs, and so on - all in components that had been realized and all seemed to be related to event handling and/or display. I had to beat it into a number of developer who were not used to Swing dev that they couldn’t manipulate realized components on non-EDT threads without expecting bugs.
OTOH, I had quite a number of components that were created on non-EDT threads, mostly because their models were created during long running communication with a non-local server. I did not see any problems with that logic that I believed was related to EDT execution. As already mentioned, the EDT the EDT is mostly about event handling, and generally the case is that this doesn’t happen until the component has been realized.
Could there be a problem with this practice? Sure, and you have to be careful anytime you write multi-threaded code, especially when it involves a UI of any sort (most UIs are like Swing in this regard). But there are valid use cases for creating Swing components off the EDT - just be careful and be aware of the possible problems.
I too would like to know why the policy change?
Comment by LCB
— 27. July 2009 @ 17:36
[...] Toni Epple » Is component creation off EDT really a bug?. [...]
Pingback by Toni Epple » Component creation off EDT is a bug!
— 28. July 2009 @ 07:53
One reason I’ve encountered for needing to do this is when initialization of a Swing component is slow. In this case the workaround is to create the component in advance in a separate thread.
OK, you could fairly claim that this is a bug in the component, but then it may be out of your control.
So I do see a need for being able to create things off the EDT.
Comment by Tim Dudgeon
— 28. July 2009 @ 12:24
One of the reasons Swing is slow with lots of lags is that things pile up on the EDT. It’s been a constant problem with GUI-based applications that we build. About six months ago we started doing asynchronous creation of objects on other threads. It just wasn’t acceptable for the user to sit there for 3 seconds of absolutely ZERO feedback while we used the EDT to create objects. So far we’ve not had any problems creating objects on background threads, although I realize that race conditions could exist. For Swing to be a first class GUI it needs to be smooth. So you either need to make it a LOT faster (unlikely) or you need to support creation of objects on background threads. Seems to me that the Swing engineers taking the easy path (”uhhh it’s a BUG if it it’s not on the EDT.”) will continue Swing’s reputation as being SLOW. Instead they need to smarten up and figure out how to make Swing smooth and fast, and asynchronous creation on background threads makes and awful lot of sense. It’s clear that without threading, Swing will never ever be able to make a smooth GUI.
Comment by John Wallace
— 31. July 2009 @ 05:19
One of the things that bothers me the most about this discussion is that the Swing engineers are willing to let Swing be a second-class GUI because making Swing smooth is hard. Not impossible. Hard. As a toolkit vendor, their job should be to make Swing easy to use and performant. Instead they multiply the problems of developers by making us adopt ever more exotic techniques to get around deficiencies in Swing. There are many cases where the process of creating a complex view takes 3-5 seconds. It’s bad enough that it takes 3-5 seconds if we can do it in the background and display a progress spinner letting the user know something is going on. Its far worse to have the UI freeze for 3-5 seconds since we can’t even display a spinner since the EDT is totally bogged down. We’ve taken to object-pooling GUI widgets that take a long time to create, but if those pools must be built on the EDT rather than a background thread, even that technique won’t work since it will cause the EDT to freeze when building those pools.
For the most part I think Swing is a good toolkit, but the Swing engineers being so out of touch with real-world usage makes wonder whether it’s worth using their code. If I can’t use their code to create a good UI of any complexity (hey, even their own SwingSet demos of trivial UIs hang for seconds at a time) then what good is it? If it can’t compete with Cocoa or .Net then Java on the desktop is stillborn — just because the Swing engineers aren’t up to solving a very solvable problem. (The problems cited for single-threading on the EDT are race conditions. They may be subtle, but race conditions are definitely solvable.)
Comment by John Wallace
— 31. July 2009 @ 17:51
@John: Object creation off the EDT is not a problem at all. You’re encouraged to do expensive operations off the EDT. It’s just the UI Components themselves that are problematic.
By the way, I haven’t heard of someone saying that Swing slow in a long, long time. And even most of the time before it was in the context of SWT by developers who didn’t actually use it… I do not agree with you in that point at all. Most of the time when a desktop application is perceived as beeing slow there’s stuff on the EDT that shouldn’t be there. By the way, most UI toolkits (SWT, Qt, NextStep, MacOS Cocoa, X Window) aren’t thread syfe and have the same limitations.
Comment by Toni
— 3. August 2009 @ 23:37
I agree with you in some points. Swing is complicated to use, and it should be easier. Stuff like SwingWorker, making it easier to work with threads in the context of the Ui should have been around (not only as code samples) earlier. Still, as soon as you know a bit about UI programming it’s no longer hard. I again agree that Swing could use some more attention and that some parts are overly complex. It’s probably not the fault of the programmers, but rather a problem of scarce resources. Right now Swing only profits indirectly from optimizations in the graphics area, but I wouldn’t expect any major improvements to the APIs. Most efforts are being put into JavaFX. Maybe this changes again with Oracle. It would make sense, since there are a lot of Swing developers out there, but since Larry seems to love JavaFX so much, I’m not sure… Teh best solution would be to make JavaFX (finally) embeddable in Swing out of the box, which would really create a unique new toolkit of it’s own right.
Comment by Toni
— 3. August 2009 @ 23:49