devxlogo

System.exit(0)

System.exit(0)

Question:
Most GUI examples show System.exit(0) as the window closing eventhandler. However, System.exit(0) is a bad way to exit applications.The specification says that the VM will exit when all the non-daemonthreads have finished. How can this be implemented so as to avoid thehard exit of System.exit(0)?

Answer:
The reason most GUI examples use System.exit(0) to terminate theapplication is twofold. First, they are examples, and it is the mostexpedient way to guarantee that the example will exit properly on allJVMs. The second reason is historical. Simply put, System.exit() wasthe only way you could exit a GUI application. Consider thefollowing. If the JVM must exit when all non-daemon threads haveterminated and the AWT thread is made a daemon thread, then yourapplication would exit immediately after main() returned. AWTprograms will never exit if you don’t use System.exit() because theAWT thread is not a daemon thread. This has been a bug in JDKs 1.0.xthrough 1.3. Sun has considered various solutions for fixing it, buthas never adopted one because it would break too many existingapplications. The latest word is that they will try to remedy thesituation in the JDK after 1.3 (Kestrel), code-named Merlin.

I should add that System.exit() is not an entirely unacceptable means ofterminating a program. In JDK 1.1, you could guarantee finalizerswould run before exiting by using System.runFinalizersOnExit(). Thiswas deprecated in JDK 1.2 because of race conditions. JDK 1.3 hasadded Runtime.addShutdownHook(), which allows you to specify cleanupcode that should be run before exiting. The problem, of course, isthat there is no way to clean up that works in JDKs 1.1 through 1.3.I believe this is further evidence that Java needs to be specifiedthrough a formal standards body, which might avoid the pitfalls Sunkeeps on creating for developers.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist