Monday, June 18, 2012

How to close Java program or Swing Application with Example

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. JVM doesn't wait for daemon thread so 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



Example of Closing Java program using System.exit()

Here is a code example of closing Java program by calling System.exit() method. Remember non zero argument to exit() method like exit(1) denotes abnormal termination of Java application.

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *Java program which terminates itself by using System.exit() method , non zero call to exit() method denotes abnormal termination.
 */

public class JavaCloseExample {
 
    public static void main(String args[]) throws InterruptedException {
   
       Thread t = new Thread(){
            @Override
           public void run(){
               while(true){
                   System.out.println("User thread is running");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(JavaCloseExample.class.getName()).log(Level.SEVERE, null, ex);
                    }
               }
           }
       };
     
       t.start();
       Thread.sleep(200);
       System.out.println("terminating or closing java program");
       System.exit(1); //non zero value to exit says abnormal termination of JVM
    }
}

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

close or terminate Java program with exampleSwing 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.

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

/**
 * Java swing program which terminates itself by calling  EXIT_ON_CLOSE and DISPOSE_ON_CLOSE
 */

public class CloseSwingExample {

    public static void main(String args[]) throws InterruptedException {

        JFrame frame = new JFrame("Sample");
        //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); won't terminate JVM if user thread running
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);

        Thread t = new Thread() {

            @Override
            public void run() {
                while (true) {
                    System.out.println("User thread is running");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(CloseSwingExample.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        };

        t.start();

    }
}


Important points about terminating or closing Java program

Few points worth noting regarding close or termination of Java application from program itself:
1) System.exit() actually calls Runtime.getRuntime().exit() method.
2) Non zero argument to exit() denotes abnormal termination of Java program.
3) Shutdown hooks are executed before Java program actually terminates.
4) There are two options to close Java Swing application one is EXIT_ON_CLOSE and other is DISPOSE_ON_CLOSE.
5) DISPOSE_ON_CLOSE doesn't terminate JVM if any user thread is running.
6) You can also implement window listener to implement your closing mechanism by using System.exit() in Swing application.

That's all on how to close or terminate Java program. we have also seen example of closing Swing application in Java and difference between EXIT_ON_CLOSE and DISPOSE_ON_CLOSE.

Other Java programming tutorial you may find useful:

1 comment :

Akshat said...

Best way to terminate Java program is not to abort it and let it complete by itself :). if you want to quit than there is only one option System.exit(), Runtime.exit() is just copy of it.

Post a Comment