原因在ExecutorService的调用shutdown() [英] Reason for calling shutdown() on ExecutorService

查看:859
本文介绍了原因在ExecutorService的调用shutdown()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到关于它颇有几分在过去的几个小时,我根本看不到任何理由(合理的理由),以呼吁ExecutorService的shutdown()方法,除非我们有一个巨大的应用程序,商店,数十座不同未使用很长一段时间执行程序的服务。

I was reading about it quite a bit in past couple hours, and I simply cannot see any reason (valid reason) to call shutdown() on the ExecutorService, unless we have a humongous application which stores, dozens and dozens of different executor services that are not used for a long time.

的唯一的事情(从我搜集)关机呢,就是做一个正常的线程执行,一旦它的完成。当正常的线程将完成了Runnable(或赎回)的run方法,它会被传递到垃圾收集被收集。随着执行人服务线程会简单地被搁置,他们将不会被选中的垃圾收集。对于关断是需要的。

The only thing (from what I gather) the shutdown does, is do what a normal Thread does once it's done. When the normal Thread will finish the run method of the Runnable(or Callable), it will be passed to Garbage Collection to be collected. With Executor Service the threads will simply be put on hold, they will not be ticked for the garbage collection. For that the shutdown is needed.

确定回到我的问题。是否有任何理由来调用shutdown上的ExecutorService很多时候,甚至submiting给它一些任务后,对不对?我想留下的人是做什么的,调用awaitTermination(),因为这是经过验证的情况下,右后。一旦我们做到这一点,我们必须重新创建一个新的ExecutorService一遍,做同样的事情。不是为ExecutorService的重用线程的整体思路?那么,为什么这么快就破坏了ExecutorService的?

Ok back to my question. Is there any reason to call shutdown on ExecutorService very often, or even right after submiting to it some tasks? I would like to leave behind the case someone is doing it and right after that calls to awaitTermination() as this is validated. Once we do that, we have to recreate a new ExecutorService all over again, to do the same thing. Isn't the whole idea for the ExecutorService to reuse the threads? So why destroy the ExecutorService so soon?

这难道不是一种理性的方式来简单地创建ExecutorService的(或情侣取决于你需要多少),然后在应用程序运行期间传递给他们的任务,一旦他们一起走,然后在应用程序退出或其他一些重要的阶段关机那些执行者?

Isn't it a rational way to simply create ExecutorService (or couple depending on how many you need), then during the application running pass to them the tasks once they come along, and then on the application exit or some other important stages shutdown those executors?

我想从一些expierienced codeRS谁做写了很多使用ExecutorServices异步code答案。

I'd like answer from some expierienced coders who do write a lot of asynchronous code using the ExecutorServices.

第二面的问题,与Android平台位较小的交易。如果你们当中有些人会说每一次,它不是最好的主意关机执行人,而你的程序在Android上,你能告诉我你是怎么处理这些停工(被specifit,当你执行它们)时,我们处理应用程序的不同事件生命周期。

Second side question, a bit smaller deals with android platform. IF some of you will say that it's not best idea to shutdown executors every time, and you program on android, could you tell me how you handle those shutdowns (to be specifit, when you execute them) when we deal with different events of application life cycle.

//因为CommonsWare评论我发的帖子中性。我真的没兴趣争论它的死亡,似乎它的领导那里。我只是有兴趣了解我问这里expierienced开发人员,如果他们愿意分享他们的expieriences。谢谢你。

//Because of the CommonsWare comment I made the post neutral. I really am not interested in arguing about it to death and it seems it's leading there. I'm only interested in learning about what I asked here from expierienced developers, if they are willing to share their expieriences. Thanks.

推荐答案

关机()方法做一件事:prevents客户端发送更多的工作了遗嘱执行人服务。这意味着所有现存的任务仍然会运行到结束,除非其他的措施会被执行。这是即使是计划任务,例如,对一个ScheduledExecutorService的真正:计划任务将无法运行的新实例。这可以在各种情况下是有用的。

The shutdown() method does one thing: prevents clients to send more work to the executor service. This means all the existing tasks will still run to completion unless other actions are taken. This is true even for scheduled tasks, e.g., for a ScheduledExecutorService: new instances of the scheduled task won't run. This can be useful in various scenarios.

让我们假设你有哪些具有运行N个任务遗嘱执行人服务的控制台应用程序。如果用户点击CTRL-C,您所期望的应用程序终止,可能正常。这是什么意思优雅?也许你想你的应用程序无法提交更多的任务执行人的服务和要等待现有的N个任务完成的同时。你可以使用一个关闭钩子作为最后的手段实现这一目标:

Let's assume you have a console application which has an executor service running N tasks. If the user hits CTRL-C, you expect the application to terminate, possibly gracefully. What does it mean gracefully? Maybe you want your application to not be able to submit more tasks to the executor service and at the same time you want to wait for your existing N tasks to complete. You could achieve this using a shutdown hook as a last resort:

final ExecutorService service = ... // get it somewhere

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Performing some shutdown cleanup...");
        service.shutdown();
        while (true) {
            try {
                System.out.println("Waiting for the service to terminate...");
                if (service.awaitTermination(5, TimeUnit.SECONDS)) {
                    break;
                }
            } catch (InterruptedException e) {
            }
        }
        System.out.println("Done cleaning");
    }
}));

这个钩子将关闭该服务,这将prevent您的应用程序提交新的任务,并等待所有现有任务关闭JVM之前完成。在等待终止将阻止5秒,返回true,如果该服务停止。这是在一个循环中完成的,这样你肯定的服务将关闭最后。该InterruptedException的获取每次吞噬。这是关机的最好的方式,得到了您的应用程序重复使用的所有遗嘱执行人的服务。

This hook will shutdown the service, which will prevent your application to submit new tasks, and wait for all the existing tasks to complete before shutting down the JVM. The await termination will block for 5 seconds and return true if the service is shutdown. This is done in a loop so that you're sure the service will shutdown eventually. The InterruptedException gets swallowed each time. This is the best way to shutdown an executor service that gets reused all over your application.

这code是不完美的。除非你是绝对肯定你的任务最终会终止,您可能要等待一个给定的超时,然后就退出,放弃了正在运行的线程。在这种情况下,它将使意义也叫执行shutdownNow()之后,在最后试图中断正在运行的线程超时(执行shutdownNow()也会给你的任务等待运行的列表)。如果你的任务是设计来应对中断,这将很好地工作。

This code isn't perfect. Unless you're absolutely positive your tasks will eventually terminate, you might want to wait for a given timeout and then just exit, abandoning the running threads. In this case it would make sense to also call shutdownNow() after the timeout in a final attempt to interrupt the running threads (shutdownNow() will also give you a list of tasks waiting to run). If your tasks are designed to respond to interruption this will work fine.

另一个有趣的情况是,当你有一个ScheduledExecutorService的执行周期性任务。停止周期性任务链中的唯一方法是调用关机()

Another interesting scenario is when you have a ScheduledExecutorService that performs a periodic task. The only way to stop the chain of periodic tasks is to call shutdown().

编辑:我想补充一点,我不会建议使用在一般情况下,上面显示一个关闭挂钩:它可以是容易出错,应该只是最后的手段。此外,如果你有很多关机挂钩注册的顺序,他们将运行是不确定的,这可能是不可取的。我宁愿让应用程序显式调用关机() InterruptedException的

I'd like to add that I wouldn't recommend using a shutdown hook as shown above in the general case: it can be error prone and should be a last resort only. Moreover, if you have many shutdown hooks registered, the order in which they will run is undefined, which might be undesirable. I'd rather have the application explicitly call shutdown() on InterruptedException.

这篇关于原因在ExecutorService的调用shutdown()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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