views:

73

answers:

3

There's a couple questions here on StackOverflow on the subject of threading with the Swing api but things still aren't clear. What is the issue with the EDT, what is the proper way to initiate a Thread with Swing and in what cases should it be used?

P.S: Any sources in terms of good practises would be appreciated.

+2  A: 

Check out the java tutorial on the event dispatch thread here and here. So the Event dispatch thread is the place where all the UI events are dealt with. This allows all the UI manipulating code to exist in one thread (the EDT) and therefore eliminate any thread safety issues.

krock
+1  A: 

I would probably start with SwingWorker.

TuxGeek
+1  A: 

This too long for a comment so I make it an answer.

One of the issue with the EDT, that is not necessarily well known, is that in quite some cases Swing shall silently eat exceptions and restart a new EDT.

There's often a wrong belief that during the lifetime of a program there's one EDT: but it's not so. Every time the EDT dies a new EDT is created.

People typically talk about "the EDT" as if there was one unique EDT running through the lifetime of the application: but it is not so. It is not uncommon at all to have a new EDT restarted several times.

Note that if it wasn't this way, all the non-trivial Swing programs wouldn't work for very long because the Swing API themselves contains quite a huge amount of bugs that do actually trigger exceptions and hence several "EDT dying / new EDT created" cycles during the lifetime of an application.

The "EDT dying / new EDT created" cycle can be trivially reproduced by crashing the EDT on purpose:

public void actionPerformed( ActionEvent e ) {
    System.out.println( "Thread ID:" + Thread.currentThread().getId() );
    System.out.println( 0 / Math.abs(0) );
}

If you attach this ActionListener to, say, a JButton, you'll see that each time you click on the button the EDT will have a new thread ID.

The fact that non-trivial Swing program do crash the EDT quite regularly due to bug in the Java API can be seen by adding a default uncaught exception handler (and by reading the huge number of Swing bugs triggering exceptions in the Sun bug parade).

This is all hidden by default to Java programmers because when these Swing API exceptions happens, a new EDT is simply started.

Note that this doesn't change the fact that lenghty computation should be run outside the EDT.

NoozNooz42