Runtime.getRuntime().addShutdownHook简介

前言:

在使用线程池的时候,偶然看到了前人的代码里出现了Runtime.getRuntime().addShutdownHook()。

作用:

jvm中增加一个关闭的钩子,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。

使用场景:

多用于内存清理,对象销毁等等。

示例:

以线程池在进程关闭时的处理。
上代码:

    private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

            @Override
            public void run() {
                close();
            }
        }));
    }

    private static void close() {
        try {
            System.out.println("clean");
            executorService.shutdown();
            System.out.println(executorService.awaitTermination(10000, TimeUnit.SECONDS));
            System.out.println("end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            final int index = i;
            try {
                executorService.schedule(new Runnable() {

                    @Override
                    public void run() {
                        System.out.println("yes" + index);

                    }
                }, 3, TimeUnit.SECONDS);
                System.out.println("add thread");
            } catch (Exception e) {
            }

        }

    }

代码的具体意思,不做展开,我们看结果(我们在第8次增加任务的时候,手动kill掉这个进程)
add thread
add thread
add thread
yes0
add thread
yes1
add thread
yes2
add thread
yes3
add thread
yes4
add thread
clean
yes5
yes6
yes7
true
end

我们可以看到,当kill掉进程之后,调用了close的方法。这个代码的作用,是当进程关闭时,我们将线程池中已经添加的任务继续执行完毕,然后关闭线程池。他的作用是防止已添加的任务丢失。

你可能感兴趣的:(Runtime.getRuntime().addShutdownHook简介)