28
According to the Java specification, much of the Swing API is not Thread-Safe and shall rotate in the Event Dispatch Thread.
Like, after initializing the GUI events are fired from within of the EDT itself, unless you are using threads in background that need to update the UI, this is not usually a problem.
But as the method main
runs on its own thread (initial), it is common to use invokeLater
to dispatch the GUI display to the EDT:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
exibirTela();
}
});
}
See that, after displaying the screen, the method main
does not execute anything else. In theory, no concurrent EDT code seems to be executed in thread leading.
My question is: There is a reason why we have to dispatch the creation of the screen to the EDT?
In the stack overflow in English I found a reference which points to the documentation saying that the thread should not create the GUI because "almost all the code that creates or interacts with Swing components should run on the EDT". Those days however I saw the code of an application that is running for almost 10 years in production. This code creates and displays the JFrame
main directly from main
; there was never any problem reported about the operation of that application.
In this sense, what would be the possible competition problems? If we do not use invokeLater
what will be rotating in the thread and what will be running on the EDT (e.g.: A JFrame
is in the thread but its events go to the EDT)?
A few years ago I programmed in Swing and I had the habit of starting the Swing interface directly in the Main Class and even it be an extension of the
JFrame
, I never had a problem, but my memory alerts me about moments that I had to lock some processes since both were executed in the same thread that started Jframe..– Delfino