Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a simple Swing application terminate when a window is shown?

Tags:

java

swing

Here's some sample code:

import javax.swing.*;

public class MyApplicatin {
    public static void main(String args[]) {
        JFrame window = new JFrame();
        window.setSize(100,100);
        window.setVisible(true);

        System.out.println("Should terminate after printing this.");
    }
}

Why doesn't this small application terminate after printing the last line?

My guess is that Swing starts a new non-daemon thread. I'm reading about having to do the GUI stuff in Java in a separate thread all the time, if Swing already uses a separate thread, why would anybody write about that?

like image 418
Georg Schölly Avatar asked Mar 21 '11 13:03

Georg Schölly


1 Answers

Why should it? Normally, when you show a Window you'll want control over when the JVM exits. And nothing in the JVM spec says that the JVM must exit when the main() method reaches the end.

Oracle has some documentation on this specific issue:

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.

One (of three) restricton on this machinery is this:

There is at least one alive non-daemon thread while there is at least one displayable AWT or Swing component within the application (see Component.isDisplayable).

This means that the JVM will not quit on its own as long as there's a displayable AWT/Swing component around.

Warning: disposing all displayable components does not necessarily mean that the non-daemon thread is gone:

It depends on the implementation if and when the non-daemon helper threads are terminated once all components are made undisplayable.

like image 98
Joachim Sauer Avatar answered Oct 03 '22 16:10

Joachim Sauer