Living Off the EDT Thanks to AOP?

Thanks to Ramnivas (see comments) for pointing me out what I was doing wrong :)

Ah, what a joyce to use cool acronyms in a blog entry title. But that's not the point. A few weeks ago, Alexander Potochkin wrote something about using an @OnEdt annotation to make Swing threading management easier. So today I wrote an AspectJ aspect to handle this and see by myself whether it could be a good solution to manage everything for the developer. First the annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public @interface OnEDT {

Then, the aspect itself:

import java.awt.EventQueue;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.swing.SwingUtilities;

public aspect OnEdtAspect {
    pointcut onEDT() : call(@OnEDT * *(..));
    void around() : onEDT() {
        if (!EventQueue.isDispatchThread()) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {

Whenever a method annotated by @OnEDT is called, it checks whether it is running in the EDT. When it's not, the method is invoked again, but in the EDT this time. The point is you can write this and be safe:

// In a thread
public void run() {
    while (...) {

private void changeTheUI(float timeValue) {
    // It's safe, we are in the EDT!

The aspect works only with methods returning void but I guess it's possible to work around this, maybe with generics. You can also go further and apply this aspect to any Swing method by defining the following pointcut:

pointcut inSwing() : call(void javax.swing.*.*(..));

Once again, it handles only void returning methods. As Joshua pointed out, this can be very dangerous when applied to the whole Swing library. Take this small example:

// In a thread
public void run() {
    Sting newText = textComponent.getText();

Woops. The first line goes into the EDT and the second line can therefore be executed before the first one!

That was only a quick and dirty hack but I think we should stick to detecting threading issues with AOP (or RepaintManager) rather than trying to address them for the developer. Performance problems left aside, there are way too many errors that can happen because of such a solution.

One Response to “Living Off the EDT Thanks to AOP?”

  1. Thanks for information.
    many interesting things