Runtime.getRuntime().addShutdownHook簡(jiǎn)介

前言:

在使用線程池的時(shí)候,偶然看到了前人的代碼里出現(xiàn)了Runtime.getRuntime().addShutdownHook()。

作用:

jvm中增加一個(gè)關(guān)閉的鉤子,當(dāng)jvm關(guān)閉的時(shí)候,會(huì)執(zhí)行系統(tǒng)中已經(jīng)設(shè)置的所有通過(guò)方法addShutdownHook添加的鉤子,當(dāng)系統(tǒng)執(zhí)行完這些鉤子后,jvm才會(huì)關(guān)閉。所以這些鉤子可以在jvm關(guān)閉的時(shí)候進(jìn)行內(nèi)存清理、對(duì)象銷(xiāo)毀等操作。

使用場(chǎng)景:

多用于內(nèi)存清理,對(duì)象銷(xiāo)毀等等。

示例:

以線程池在進(jìn)程關(guān)閉時(shí)的處理。
上代碼:

    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) {
            }

        }

    }

代碼的具體意思,不做展開(kāi),我們看結(jié)果(我們?cè)诘?次增加任務(wù)的時(shí)候,手動(dòng)kill掉這個(gè)進(jìn)程)
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

我們可以看到,當(dāng)kill掉進(jìn)程之后,調(diào)用了close的方法。這個(gè)代碼的作用,是當(dāng)進(jìn)程關(guān)閉時(shí),我們將線程池中已經(jīng)添加的任務(wù)繼續(xù)執(zhí)行完畢,然后關(guān)閉線程池。他的作用是防止已添加的任務(wù)丟失。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容