Sunday, June 18, 2017

How to Close Java Program or Swing Application with Example

In order to close the 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 the 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 causes 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 denotes abnormal execution and its result returned by java command to the caller. 

In this java tutorial, we will see an example of closing both the Java program and the Java Swing application. This is also a good swing interview questions which you can ask any GUI developer and my second article in the swing after writing invokeAndWait vs invokeLater

And, if you are new to Java Swing and GUI Programming world then I also recommend you go through Java Swing (GUI) Programming: From Beginner to Expert course by John Purcell on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java Swing and GUI coding online.


1. Example of Closing Java program using System.exit()

Here is a code example of closing the Java program by calling System.exit() method. Remember non zero arguments 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 the main method and start it which prints “User thread is running” and then main thread sleep for 200 Millisecond, till then 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.



2. How to close Java swing application from the program

close or terminate Java program with exampleSwing application mostly uses JFrame as a top-level container which provides two options to close swing GUI application from code. The first option which is the default is EXIT_ON_CLOSE which terminates the Java swing GUI program when you click the close button on the JFrame window. 

Another option is DISPOSE_ON_CLOSE which terminates JVM if the last displayable window is disposed of. 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 uncommenting DISPOSE_ON_CLOSE in your IDE and you can see user thread running even after clicking on the close button. here is a complete code example of closing the 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();

    }
}


3. Important points about terminating or closing Java program

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

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

Further Reading
Java Swing (GUI) Programming: From Beginner to Expert
Mastering Java Swing - Part 1
The Complete Java MasterClass

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