Java ThreadPoolExecutors idle thread shutdown - calling custom cleanup code

风格不统一 提交于 2019-12-11 09:59:18

问题


Per the ThreadPoolExecutor doc (Java ThreadPoolExecutor), if I create an executor service like so:

new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);

and when #threads > corePoolSize, idle threads will be killed. I wanted to call some application specific cleanup code when the ThreadPoolExecutor kills any thread. I wasn't able to get a clear way to do so. Appreciate any help. Thanks in advance.


回答1:


the correct way to do this is by extending Thread and running your cleanup code after the run() method returns, like so:

    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r) {
                @Override
                public void run() {
                    super.run();
                    //DO YOUR CLEANUP HERE
                }
            };
        }
    };
    new ThreadPoolExecutor(1, 10, 10, TimeUnit.SECONDS, workQueue, threadFactory);

interrupt will almost definitely not get called in your scenario, since it will only be called when shutting down an active executor (and even then, not always).

by calling cleanup directly after run your cleanup code gets called right before the thread dies (a thread dies after the runnable's run() method returns).



来源:https://stackoverflow.com/questions/25104668/java-threadpoolexecutors-idle-thread-shutdown-calling-custom-cleanup-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!