Wednesday, May 19, 2010

Aspects as a programming aid

I have recently been playing around with Aspect Oriented Programming, specifically AspectJ, as a tool for Java development. Like many Java programmers, I played around with AOP what it was going through the hype cycle in 2002 and 2003. Since then, it seems that the use of Aspects as a production-level tool is on the rise, even if its use is indirect such as in a JEE container like Spring or framework like Spring Roo.

The initial idea of Aspects sounds cool: you can weave in code that queries the dynamically created abstract syntax tree of a Java application intercepting method calls and injection new functionality. Your aspects are modular, they are reused by your pattern-matching based application (interception), and you don't have to touch (pollute) your Java source. The coolness wears off when you realize your pattern matching queries are limited to high-order abstractions like packages, classes and methods, and that the ability to play with the actual code and context that you intercept is practically not available.

I had been tinkering with some tracing aspects on and off for the last month or two, but with no real enthusiasm. The other day I listened to a podcast on AspectJ and Spring AOP with Ramnivas Laddad, the author of AspectJ in Action. The podcast got me excited again, and I realized that it may in fact be directly useful to help with some sticky race condition bugs on which I've been burning brain cycles.

One aspect in particular that I'm sure others will find useful is a tracer that will detect violations of the 'single thread rule' in Swing. Specifically, those cases when threads other than the Event Dispatch Thread are touching swing objects. See below for a snippet I've been playing around with, based on a code example provided by Anders Prisak in Using AspectJ to detect violations of the Swing single thread rule. Alexander Potochkin provides some additional details in Debugging Swing, the final summary.



The cases the aspect catches are crude, but provide a good starting point for digging around. I use Eclipse with the AspectJ Eclipse plug-in AJDT. In such a configuration, simply configure your existing Swing project as an AspectJ project, drop in the aspect into the default package and run your application to see all the violations printed to stdout. See the AspectJ docs for additional details for weaving the aspect under other circumstances.

Progress has been good, although the subtle and creative use of the syntax may take some time to master. Some resource I found useful to grep while hacking together some tracing aspects included the The AspectJ Programming GuideThe AspectJ 5 Development Kit Developer's Notebook, and the AspectJ FAQ.

0 comments: