Java中注册进程退出时的清理函数

java里利用addShutdownHook可以添加一个线程,在jvm关闭时调用,执行一些清理工作

public static void main(String[] args) throws InterruptedException {
		Thread shutdownHook = new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("jvm going down!do something here!");
			}

		});
		Runtime.getRuntime().addShutdownHook(shutdownHook);

		while (true) {
			TimeUnit.SECONDS.sleep(1);
		}

	}


但是这个线程不能保证总是工作.
引用
In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

所以kill -9的时候,就不能保证这个清理函数的执行了

你可能感兴趣的:(java)