柚子da

导航

 

https://stackoverflow.com/questions/8722826/when-do-i-need-to-call-this-method-runtime-getruntime-addshutdownhook

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).

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.
	try (GpehEventExtractor extractor = new GpehEventExtractor(props)) {

			Runtime.getRuntime().addShutdownHook(new Thread() {
				@Override
				public void run() {
					System.out.println("Shutdown hook ran!");
					try {
						extractor.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});

			while (true) {
				try {
					Thread.sleep(1000 * 60);
				} catch (Exception e) {
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

  

posted on 2017-11-03 10:31  柚子da  阅读(233)  评论(0)    收藏  举报