| ||||
Copyright 1999 Sams Publishing |
|
Using SwingUtilities.isEventDispatchThread() |
If you have code that must (or must not) be called by the event thread, you can use the SwingUtilities.isEventDispatchThread() method: |
public static boolean isEventDispatchThread () |
This static method returns true if the thread that invokes it is the event thread, and returns false if it is not. |
If it is critical that only the event thread calls a particular method, you might want to put some code like this at the beginning of the method: |
if ( SwingUtilities.isEventDispatchThread () == false) { |
throw new RuntimeException( |
only the event thread should invoke this method); |
} |
This way if any thread other than the event thread calls the method, a RuntimeException is thrown. This step can help safeguard against dangerous code that works most of the time when called by a thread other than the event thread. |
A downside to this method is that it takes a little bit of time to execute. If you have some code where performance is critical, you might want to skip this check. |
| |||
Toc |