【java基础】如何设计java应用程序的平滑停止
java应用程序退出的触发机制有:
1.自动结束:应用没有存活线程或只有后台线程时;
2.System.exit(0);
3.kill 或 ctrl+C;
4.kill -9 强制退出;
?
如何做到应用程序平滑停止程序的退出就像关机一样,我们希望关机时平滑关机,保证所有应用程序的数据都保存了。就像现在在写得blog,希望关机的时候能被保存好到草稿箱里。
我们的的java程序中经常有一种常驻的任务或服务,如消息消费端、服务提供者,我们期望停止也是平滑的不会出现事务执行到一半产生脏数据。
?
java对这块的支持是通过钩子线程实现。每个java进程都可以注册钩子线程,钩子线程程在程序退出的前被执行(kill -9强制退出除外)。注册钩子线程代码如下:
import java.io.File;import java.io.IOException;public class ShutdownFileTest { public static void main(String[] args) { // 启动子线程 new Thread() { public void run() { while (true) { try { Thread.currentThread().sleep(1000); System.out.println("sub thread is running"); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); //启动shutdownfile监听线程 new Thread() { public void run() { File shutDownFile = new File("a.shutdown"); // create shut down file if (!shutDownFile.exists()) { try { shutDownFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // watch for file deleted then shutdown while (true) { try { if (shutDownFile.exists()) { Thread.currentThread().sleep(1000); } else { System.exit(0); } } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); }}?3.打开一个端口,监听端口里的命令,收到命令后调用System.exit。
这个似乎不常见,也比较麻烦。
4.JMX
通过JMX的mbean远程控制来实现。
在这个链接里有看到例子:how-to-stop-java-process-gracefully
?
?