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
188 views
in Technique[技术] by (71.8m points)

java - When do I need to call this method Runtime.getRuntime().addShutdownHook()

When do I actually need call this method Runtime.getRuntime().addShutdownHook() and when or why I need to shutdown my application. Could anyone please explain me this by giving some example.

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As far as I know, I will explain this below. You can google it and find lot of information too.

addShutdownHook() will register some actions which is to be performed on a Program's termination. The program that you start ends in two ways:

  1. the main thread (Root) ends its running context;
  2. the program meets some unexpected situation, so it cannot proceed further.

If you add a ShutdownHook, the hook will start a thread that will start running at time of termination only. For example:

 Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        System.out.println("Running Shutdown Hook");
      }
    });

will print a Running Shutdown Hook at the time of program termination at any point. You might even call a System.exit(0).

For examples, you can google, there are enough of them. And the question 'When should you use this' is like asking 'What does catch do in a try-catch statement'.

You might have many situations like:

  • your program had created many temporary files in filesystem you want to delete it;
  • you need to send a distress signal to another process/machine before terminating;
  • execute any clean-up actions, logging or after-error actions on unexpected behaviours.

All this will be needed for some point of time.

For examples you can go in here Example 1 or Example 2


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

...