Check if an EDT stream is needed?

I have an interface implemented with Swing. One component does some work, which may take some time, so I use SwingUtilities.invokeLater . However, I read the old code and found this in the ActionListener :

 if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { // code X } }); } else { // code X } 

I thought this made sense as it separates code X from EDT. However, I found it error prone since I used it a couple of times, and both times I forgot the else part.

The question is: do you need SwingUtilities.isEventDispatchThread() validation? Or could I suggest that I'm not in EDT, but always using invokeLater ?

Many thanks.

+4
source share
4 answers

The call later is excellent, even if you are on the EDT, however, it certainly changes the time of events, so you must be sure that you were not dependent on the code sequence here when you were on the EDT. In this case, a simple way to avoid forgetting else is to wrap the call in the utility:

 public static void invokeInDispatchThreadIfNeeded(Runnable runnable) { if (EventQueue.isDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } 

This way you will never forget else .

Also, overall in your idom, repeating code x is a very bad idea, as you can fix or improve this code later, and you will only do this in one place, leaving the error in another.

+14
source

I believe that for your specific use case, the check for isEventDispatchThread() not needed. A direct invokeLater() call will not create a new thread, so this will not result in performance invokeLater() .

+2
source

The code really needs to know whether it is on the EDT or not (if relevant). Therefore, java.awt.EventQueue.isDispatchThread should be left as claims.

0
source

Just if you have in your code a thread (A) that is started by EDT, and in this thread (A) you have another thread (B) that should change your GUI, in this case you need to use invokeLater on threads (B) . However, if you are modifying your GUI on the first thread (A), there is no need to use invokeLater.

0
source

Source: https://habr.com/ru/post/1307556/


All Articles