java add hook_java 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:

the main thread (Root) ends its running context;

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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值