Saturday, March 22, 2008

why Swing is not thread safe and AWT is

Simple answer is - "that's the design choice the Swing team made". It is a well-known fact that writing thread safe API/library is more difficult and inefficient.
So to simplify the implementation of Swing library they chose it to be not thread safe. The argument being that most of the GUI related work happens in the callbacks from the GUI which happen on the single GUI thread anyways. Granted - for long running tasks the user will have to do more work if he/she wants to do multithreaded activity. Not making Swing thread safe allowed them to implement the Swing which covered a lot more ground (new controls, layouts, keyboard actions, layered pane etc) in a short amount of time.

It is not that bad though - Swing does provide a mechanism to deal with the issues of threading -

javax.swing.SwingUtilities.invokeLater(Runnable ...);
javax.swing.SwingUtilities.invokeAndWait(Runnable ...);
javax.swing.JProgressBar class
javax.swing.ProgressMonitor
javax.swing.ProgressMonitorInputStream
SwingWorker
For more explaination of why they made that decision please see the following URLs:

http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads3.html
The AWT is based on the OS's WIndowing System's peer objects which are inherently thread safe. That is why AWT is thread safe.

One can argue though that they should have provided factory methods (similar to collections framework) or subclasses to get thread safe versions of the Swing classes - for example, TSJTextField or TSJTree where the "TS" stands for 'thread safe'

0 comments: