Friday, October 2, 2009

Java Swing Threading

I've recently spoken with a few developers that were writing Swing apps (some for the first time) but were not familiar with the Swing threading model and the event dispatch thread, so I thought I'd review some of the basics. The main rule of Swing programming is that any code that updates the GUI (this applies only after a component has been realized, meaning its paint method has been called) must be invoked on the event dispatch thread (EDT). This can be accomplished using the methods SwingUtilities.invokeLater and SwingUtilities.invokeAndWait to run tasks on the EDT asynchronously and synchronously respectively. There are some exceptions to the rule, and Sun details those in an article http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html#exceptions (that whole article is a very good explanation of Swing threading as well).

While this does sound like a straight forward rule, there are some easy ways to get into trouble. One of these ways is when code is updating a GUI's model, which in turn updates the GUI component, that code must be invoked on the EDT. For example, calling model.setDataVector on the DefaultTableModel to update the data in a table must be called from the EDT. Even though you are just updating the model, the model fires an event that updates the GUI (note that some GUI libraries may already handle this for you, but it's not safe to assume this in general).

Violating this rule can cause unpredictable effects. Just like any threading error, reproducing and debugging the problem can be very difficult, so be sure to obey this rule religiously.

No comments:

Post a Comment