如何在退出应用程序时关闭所有Executors? [英] How to shut down all Executors when quitting an application?

查看:624
本文介绍了如何在退出应用程序时关闭所有Executors?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Brian Goetz的Java并发性实践,JVM不能退出,直到所有(nondaemon)线程都终止,因此无法关闭Executor可能会阻止JVM退出。



如果周围有Executors,System.exit(0)不一定按预期工作。看起来有必要放一些

  public void stop(){exec.shutdown()} 

方法到包含Executors的所有类,然后在应用程序即将终止时调用它们。这是唯一的方法,还是有某种快捷方式来关闭所有的Executors?

解决方案

他们都,没有。另外,你应该调用 shutdownNow()而不是 shutdown(),否则你可能会等一会儿。 / p>

你可以做什么,我想,是当你创建Executor,注册它在一个中心的地方。然后,当关闭时,只需在该中心对象上调用 shutdown(),然后可以终止每个已注册的执行器。



如果你使用Spring,那么你可以利用它的工厂bean,为你创建和管理Executors。这包括在应用程序退出时正常关闭它们,并节省您自己管理它们。


According to Brian Goetz's Java Concurrency in Practice JVM can't exit until all the (nondaemon) threads have terminated, so failing to shut down an Executor could prevent the JVM from exiting.

I.e. System.exit(0) doesn't necessarily work as expected if there are Executors around. It would seem necessary to put some kind of

public void stop() { exec.shutdown() }

methods to all classes that contain Executors, and then call them when the application is about to terminate. Is this the only way, or is there some kind of shortcut to shut down all the Executors?

解决方案

There's no shortcut to do them all, no. Also, you should probably call shutdownNow() rather than shutdown(), otherwise you could be waiting a while.

What you could do, I suppose, is when you create the Executor, register it in a central place. Then, when shutting down, just call shutdown() on that central object, which in turn could terminate each of the registered executors.

If you use Spring, then you can take advantage of its factory beans which create and manage the Executors for you. That includes shutting them down gracefully when the application quits, and saves you having to manage them yourself.

这篇关于如何在退出应用程序时关闭所有Executors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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