Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why should Swing GUI code be placed on the EDT?  RSS feed

 
Evert DeBoer
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to what I read, “when programming in Swing, your GUI creation code should be placed on the Event Dispatch Thread (EDT). This will prevent potential race conditions that could lead to deadlock.” (See below for code.)

Why is this? How could making a GUI lead to deadlock?


 
Campbell Ritchie
Sheriff
Posts: 53736
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Find a copy of Horstmann and Cornell Core Java2 (vol I) and it says that it has never proven possible to create a thread‑safe GUI framework. They show the example of an input from a different thread which throws array out of bounds exceptions. That is why you should always access GUI components via the same thread, and Java® uses the EDT.
 
Evert DeBoer
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. But if my entire program runs in one thread (i.e. I never create any threads), do I still need the above code to create a GUI?
 
Campbell Ritchie
Sheriff
Posts: 53736
127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.

You may find the JVM moves the GUI execution onto the EDT. I am not sure. Then you are running two threads, and you have the possibility of calling things twice.

Try a Thread.currentThread() call and print its name. That will show whether you are on the EDT. Try starting a GUI from the main method, then call this sort of thing:-
System.out.println(1 / 0);
See whether the GUI vanishes after that Exception.
 
Rob Camick
Ranch Hand
Posts: 2752
11
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
99.9% of the time simply creating components and adding them to a GUI will not cause a problem. But when/if it does cause a problem you don't want to waste time trying to find a problem that randomly occurs. So to be safe do all Swing interactions on the EDT.
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Try a Thread.currentThread() call and print its name. That will show whether you are on the EDT.

Or use SwingUtilities#isEventDispatchThread().
 
Piet Souris
Rancher
Posts: 1782
54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For some very readable stuff, read the Oracle tutorials:

http://docs.oracle.com/javase/tutorial/essential/concurrency/

and

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

Greetz,
Piet
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!