为什么ThreadPoolExecutor最终确定调用关闭而不是关闭 [英] Why ThreadPoolExecutor finalize invokes shutdown and not shutdownNow

查看:619
本文介绍了为什么ThreadPoolExecutor最终确定调用关闭而不是关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ThreadPoolExecutor中的完成方法如下所示.

Finalize method in class ThreadPoolExecutor Looks like below.

protected void finalize()  {
    shutdown();
}

考虑下面的程序,其中线程永不终止

Consider below program in which thread never terminates

ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(new Runnable() {
        @Override
        public void run() {
            try {
                new SynchronousQueue<String>()
                        .put("will never get removed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    executorService = null;
    System.gc();

}

在这种情况下,shutdownNow会比shutdown更好,至少在这种情况下,JVM可能已经退出.

In such case shutdownNow would have been better choice than shutdown at least JVM could have exited in that case.

更新:

为什么finalize调用shutdown方法的唯一可能解释是,如果程序员未明确调用它,则它将在GC作为防御机制时被调用.我发现这种机制存在缺陷,因为在上述情况下,JVM不会终止.

Only possible explanation of why finalize calls shutdown method is if programmer does not call it explicitly it will get called while GC as a defensive mechanism. I see flaw in this mechanism since in above case JVM will not be terminated.

推荐答案

首先,让我问一个问题:为什么要合并一个永不终止的线程?您汇集对象以重用它们.

First, let me ask you a question: Why would you need to pool a thread that never terminates? You pool objects to reuse them.

java之所以调用shutdown,是为了给线程提供一个优雅终止的机会.

The reason why java calls shutdown, is to give the threads the oportunity to terminate gracefully.

如果需要在无限循环中运行线程,则您的线程应检查Thread.currentThread().isInterrupted()是否返回false,然后从run()返回.

If you need to run a thread in an infinite loop, then your thread should check that Thread.currentThread().isInterrupted() returs false, and then return from run().

在显示的示例中,您可能希望将方法offer()与超时方法(而不是put())一起使用.

In the example you show, you might want to use the method offer() with a timeout, rather and put().

在大多数情况下,您可以扩展ThreadPoolExecutor并在终结器中调用shutdownNow().

Wost case scenario, you can extend ThreadPoolExecutor and call shutdownNow() in the finalizer.

这篇关于为什么ThreadPoolExecutor最终确定调用关闭而不是关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆