Java EDT - How to see if your code is running on the Java Event Dispatch Thread

Java Swing FAQ: How can I tell if my Java/Swing code is running on the Event Dispatch Thread (EDT)?

I was just reading through a terrific book about Swing programming named Filthy Rich Clients, and I was reminded of a Swing technique I used to use from time to time to determine if a certain portion of code was running on the Java EDT.

Every once in a while I’d get in a discussion with another developer about whether a section of Java code was running on the EDT, so I’d say,“Let’s put a little code in here and find out for sure.” (It’s amazing how a little bit of code can settle an argument, one way or another.)

Here’s the Java EDT code snippet I just saw in the Filthy Rich Clients book:

if (SwingUtilities.isEventDispatchThread()) {
    code.run();
} else {
    SwingUtilities.invokeLater(code);
}

As you can see, using this static method of the SwingUtilities class is very simple. The authors recommend using this code snippet if you’re not sure if your code is running on the EDT or not. Although I haven’t done this before, I can see where it can be a valid approach, especially if your code block can be run from different methods of your application.

General Java EDT test

But for a simpler application, if you’re just trying to determine whether a section of code is running on the Java EDT, I just add some debug code in the if/then test, like this:

if (SwingUtilities.isEventDispatchThread()) {
    System.err.println("Is running on EDT");
} else {
    System.err.println("Is not running on EDT");
}

At the very least, I think this little snippet of Java/Swing code is cool because it can help you understand how the Java EDT works.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.