Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

Java shutdown hook

I have added the following code to my program:

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("exit");
    }
}){});

I however do not see the message. Additional information: I am running the program from inside the Netbeans IDE on Java 7.

EDIT: I forgot to add that there is a global Thread that keeps the program alive. I close it by pressing the [x] in Netbeans lower right corner.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The JVM can shutdown in either an orderly or abrupt manner. A shutdown hook runs for an orderly shutdown: when the last normal thread terminates, someone calls System.exit or by other platform specific means (such as typing Ctrl-C).

Shutdown hooks will not run for an abrupt shutdown of the JVM. As you are pressing the [x] in Netbeans lower right corner, this will cause an abrupt shutdown of the JVM and this is why the shutdown hook was not started.

For example :

public class ShutdownHook {
public void attachShutDownHook() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println("exit");
        }
    });

}

public static void main(String[] args) {
    ShutdownHook sample = new ShutdownHook();
    sample.attachShutDownHook();
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

If you run the above code, and let the program complete normally, you will see exit printed on the console. But if you press [x] (within 3 secs) to close it abruptly, the shutdown hook will not run and there will not be any exit printed on the console.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...