This post originated from an RSS feed registered with Java Buzz
by Scott Delap.
Original Post: Using AspectJ to Solve Swing Threading Issues
Feed Title: ClientJava.com
Feed URL: http://www.clientjava.com/archives/wireless_mobile.rdf
Feed Description: Client/Desktop Related Java Development
Solutions to server related tasks are often used to demonstrate good uses of AOP. However, desktop applications can also gain from its use. Manning's AspectJ in Action (Chapter 9) features using AOP to detect Swing Single Threading Rule violations and to provide a transparent way to fix them. You can download the source from the book on Manning's website. Here is a brief rundown of what you'll find.
The aspect itself isn't that complicated. Basically, it is written to look for any method call:
1. On a class that extends JComponent
2. On a class that contains or extends a class that contains "Model" in the name.
3. On javax.swing.text.Document or a class that extends it.
There is also a set of excludes for known thread save methods such as revalidate. This is the same general ruleset I used when writing my thread checking repaint manager. Once these method calls have been trapped the single threading rule can be addressed. If a method call originates from a non swing thread it can be posted to the EDT using one of the SwingUtilities methods. The aspect evaluates whether the method call has a return value in order to determine whether SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() is used. The chapter also mentions that additional features could be added including thread pooling and progress notifications.
The downsides with using this approach is that your thread safety is only as good as the ruleset you write. If you have components not extending JComponent or custom models that don't follow easily identifable naming conventions, things get complicated.
There is also the tendency to not think about why/how you are threading things if something else is taking care of the details for you without forcing you to code to an interface or API. If you have a highly multi-threaded application, it is probably worth your while to invest in a Jobs type API like Eclipse has. This provides priority levels, resource dependencies, and a clean progress API. Having to write code to implement such features, will likely result in better application design patterns.