The invokeAndWait() allows you to publish a Runnable job that must be run on the EDT, but blocks the current thread and waits for the EDT to complete the task.
But there is a deadlock potential in invokeAndWait (), since thread code is created in any code. If the calling code contains some lock (explicitly or implicitly) that the code calls through invokeAndWait () is required, then the EDT code will wait for the EDT to release the lock, which cannot be because the non-EDT code is waiting for the completion of the EDT code, and the application will hang.
As we can see here, a change in the JLabel component passed to the pending non-EDT.
Instead, we can use
invokeLater() takes care of creating and invokeLater() special event that contains Runnable. This event is processed on the EDT in the order in which it was received, like any other event. When the time comes, it is sent by running the Runnables run () method.
SwingUtilities.invokeLater(new Runnable() { public void run() { label.setText("Refreshing in: " + i + " seconds."); } });
OR
isEventDispatchThread() , which returns true if the calling code is currently executing in EDT, otherwise false.
Runnable code= new Runnable() { public void run() { label.setText("Refreshing in: " + i + " seconds."); } } ); if (SwingUtilities.isEventDispatchThread()) { code.run(); } else { SwingUtilities.invokeLater(code); }
source share