简体   繁体   中英

Java Force Close Program

How can I programatically force close the program upon exit. I've added the shutdown hook which calls a System.exit(0) but it seems to have problems executing that. The javaw.exe process keeps running in memory even though the Jframe is closed and the shutdown hook was executed.

Additionally, when I manually close the batch file running the program, windows throws the Force Close message. image: http://i.imgur.com/gy57OEV.png

Calling System.exit() in a shutdown hook is pointless. The JVM has already decided to shutdown before the hook is called. I imagine that calling System.exit() from a shutdown hook could be problematic ...

Presumably, the reason that your application is not closing is that your application has created other threads, and they are still alive.

One way to handle this is to have the JFrame close event (or the close button) trigger something that starts the JVM shutdown. Your f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) code is one way to do that. It would call System.exit ... and THAT would run any shutdown hooks as the JVM shuts down.

Another way is to mark the other threads as "daemon" threads, which means that they won't stop the JVM from deciding to shut down. (Normally, the JVM pulls the plug if there are no live non-daemon threads. For a single-threaded application, that means your "main" thread ... )


As a matter of interest, here's why a System.exit() call is problematic in a shutdown hook.

The javadoc says that System.exit() is equivalent to System.getRuntime().exit() , and the javadoc for the latter says this:

" If this method is invoked after the virtual machine has begun its shutdown sequence then if shutdown hooks are being run this method will block indefinitely. "

So if you call System.exit() within a shutdown hook, that is sufficient to cause the hook to block indefinitely. And that will cause the shutdown sequence to stall.

System.exit() works properly in JOptionPane scenarios:

Object[] options={"YES","NO"};
int selection= JOptionPane.showOptionDialog(this, "Message input", "Title",
        JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, 
        options[1]);
if(selection==JOptionPane.YES_OPTION){
    reset();
}
else if(selection==JOptionPane.NO_OPTION){
    System.exit(0);
}

but, as stated above f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); is still present in my main method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM