Why is Swing threading model considered wrong and how should it be? [closed]

I heard many times that Java Swing threading model is wrong. I don't fully understand why, I know that the problem is related to the fact that you can draw on a Drawable from another thread other than the main UI thread. I know that there are utility functionalities like SwingUtilities.invokeAndWait and SwingUtilities.invokeLater that let you do your painting in a Runnable, that in turn is run by the Event Dispatcher thread. I guess that this way you ensure that painting is done synchronously and this doesn't leave the buffer in an incosistent state.

My question is: how do "good" UI toolkits behave? What solutions are adopted?


Solution 1:

Brian Goetz's Java Concurrency in Practice,

9.1 Why are GUIs single-threaded?:

...In the old days, GUI applications were single-threaded and GUI events were processed from a “main event loop”. Modern GUI frameworks use a model that is only slightly different: they create a dedicated event dispatch thread (EDT) for handling GUI events. Single-threaded GUI frameworks are not unique to Java; Qt, NextStep, MacOS Cocoa, X Windows, and many others are also single-threaded. This is not for lack of trying; there have been many attempts to write multithreaded GUI frameworks, but because of persistent problems with race conditions and deadlock, they all eventually arrived at the single-threaded event queue model in which a dedicated thread fetches events off a queue and dispatches them to application-defined event handlers...

Solution 2:

For SWT: http://book.javanb.com/swt-the-standard-widget-toolkit/ch05lev1sec7.html

SWT implements a single-threaded user interface model that is typically called apartment threading. In this model, only the user interface thread can invoke user interface operations. This rule is strictly enforced. If you try to access an SWT object from outside the user interface thread, you will get an SWTException("Invalid thread access").

So SWT is single-threaded too. But it takes the extra step to forbid any changes to the UI outside of the UI thread. Consider the alternative in Swing where modifying the UI from somewhere else is allowed but will produce sooner or later unexpected results that will confuse the newbie programmer who will then learn that Swing is single-threaded the "hard" way.

Also, if your design is not clear, you may end up with situations where you think you are in the correct thread but in actuality you are not. You can also be unable to tell reliably what threads will access a specific piece of code, but then you probably have a serious design issue in you own code anyway.

Other than that, I can't imagine other reasons why Swing's threading model would be considered "wrong".