From which thread should System.exit() be called in a Swing-app?

You should not be calling System.exit() if you can help it.

The best way to exit a java process is to let all threads exit normally. This will terminate the VM.

In your main JFrame, you should setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).

Then you can call frame.dispose() to close the JFrame and exit the EDT.


Since the VM is terminated after the System.exit() call I don't think it makes any difference from which thread the call is being made.


You can call it from any Thread, but it is kind of rude to use it IMHO. The virtual machine will be terminated, no matter what else is running.

I prefer to dispose() or just close (having setDefaultCloseOperation(DISPOSE_ON_CLOSE)) any displayed window (JFrame, JDialog, ...). If there are only daemon threads running, the virtual machine will be terminated. If there is some live non-daemon thread, the JVM will not terminate and the thread can finish its work.
Doing so, I always can include (parts of) one program in another without having to worry if one of them will accidentally terminate the other.

There are very few situation where the JVM really needed to be "killed"...

Tags:

Java

Swing