Monday, June 18, 2012

In order to close Java program we need to consider which kind of Java application it is?, because termination of Java application varies between normal core java program to swing GUI application. In general all Java program terminates automatically once all user threads created by program finishes its execution, including main thread.JVMdoesn't wait for daemon threadso as soon as last user thread finished, Java program will terminate. If you want to close or terminate your java application before this your only option is to use System.exit(int status) or Runtime.getRuntime().exit(). This cause JVM to abandon all threads and exit immediately. Shutdown hooks are get called to allow some last minute clearing before JVM actually terminates. System.exit() also accept an int status parameter where a non zero value denote abnormal execute and its the result returned by java command to caller. In this java tutorial we will see example of closing both Java program and Java Swing application. This is also a good swing interview questions which you can ask to any GUI developer and my second article in swing after writing invokeAndWait vs invokeLater

Output:
User thread is running
User thread is running
terminating or closing java program
Java Result: 1//1 is what we passed to exit() method

This Java program first creates a Thread in main method and start it which prints “User thread is running” and than main thread sleep for 200 Milli second, till than other user thread is running and printing but once main thread woken up it terminates the program by calling exit() method of java.lang.System class.

How to close Java swing application from program

Swing application mostly uses JFrame as top level container which provides two option to close swing GUI application from code. First option which is default is EXIT_ON_CLOSE which terminates Java swing GUI program when you click close button on JFrame window. Another option is DISPOSE_ON_CLOSE which terminates JVM if last displayable window is disposed off. Difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE is that if you have a non daemon thread running it will not be closed in case of DISPOSE_ON_CLOSE, while EXIT_ON_CLOSE terminate JVM even if user thread is running. run the below example by un comment DISPOSE_ON_CLOSE in your IDE and you can see user thread running even after clicking on close button. here is a complete code example of closing Swing application in Java.