(original) (raw)

AWT Threading Issues

Listeners and threads

Unless otherwise noted all AWT listeners are notified on the event dispatch thread. It is safe to remove/add listeners from any thread during dispatching, but the changes only effect subsequent notification.
For example, if a key listeners is added from another key listener, the newly added listener is only notified on subsequent key events.

Auto-shutdown

According toThe Java™ Virtual Machine Specification, sections 2.17.9 and 2.19, the Java virtual machine (JVM) initially starts up with a single non-daemon thread, which typically calls the main method of some class. The virtual machine terminates all its activity and exits when one of two things happens:

This implies that if an application doesn't start any threads itself, the JVM will exit as soon as main terminates. This is not the case, however, for a simple application that creates and displays a java.awt.Frame:

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setVisible(true);
     }

The reason is that AWT encapsulates asynchronous event dispatch machinery to process events AWT or Swing components can fire. The exact behavior of this machinery is implementation-dependent. In particular, it can start non-daemon helper threads for its internal purposes. In fact, these are the threads that prevent the example above from exiting. The only restrictions imposed on the behavior of this machinery are as follows:

Implementation-dependent behavior.

Prior to 1.4, the helper threads were never terminated.

Starting with 1.4, the behavior has changed as a result of the fix for4030718. With the current implementation, AWT terminates all its helper threads allowing the application to exit cleanly when the following three conditions are true:

The Java™ Virtual Machine Specification guarantees that the JVM doesn't exit until this thread terminates.