Why do I have to call System.exit() from my main method?

Alex Chaffee

Unfortunately, certain system threads are started as regular threads, not daemon threads. One example is the AWT thread. That means that if your app opens a window, then even if that window is closed, the AWT thread continues, so your app will never quit on its own.

There are many cases where a Java program will quit on its own when main() exits, but there are also many sneaky cases where a thread is launched without your knowledge by a library routine. Database Connection Pools are notorious for doing this.

A warning: Make sure you only call System.exit() when you're really really sure all background threads have stopped processing. Otherwise the threads will be stopped prematurely, and may leave things in a bad state (for instance, if they're halfway through writing a file).