在Tomcat中从servlet生成线程的推荐方法是什么 [英] What is recommended way for spawning threads from a servlet in Tomcat

查看:101
本文介绍了在Tomcat中从servlet生成线程的推荐方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复一次!我使用Tomcat作为我的服务器,并想知道什么是在确定性结果的servlet中生成线程的最佳方法。我正在从servlet操作运行一些长时间运行的更新,并希望完成请求并在后台进行更新。而不是添加像RabbitMQ这样的消息中间件,我想我可以生成一个可以在后台运行并在自己的时间内完成的线程。我在其他SO线程中读到服务器终止服务器生成的线程,以便它能够很好地管理资源。

Probably a repeat! I am using Tomcat as my server and want to know what is best way to spawn threads in the servlet with deterministic outcomes. I am running some long running updates from a servlet action and would like for the request to complete and the updates to happen in the background. Instead of adding a messaging middleware like RabbitMQ, I thought I could spawn a thread that could run in the background and finish in its own time. I read in other SO threads that the server terminates threads spawned by the server in order for it to manage resources well.

在使用Tomcat时,是否有推荐的方法来生成线程,后台作业。我也使用Spring MVC作为应用程序。

Is there a recommended way of spawning threads, background jobs when using Tomcat. I also use Spring MVC for the application.

推荐答案

您最安全的选择是使用带有最大线程数的应用程序线程池,所以任务将在必要时排队。 ExecutorService 对此非常有帮助。

Your safest bet is using an applicaton wide thread pool with a max amount of threads, so that the tasks will be queued whenever necessary. The ExecutorService is very helpful in this.

在应用程序启动或servlet初始化时,使用执行者类:

Upon application startup or servlet initialization use the Executors class:

executor = Executors.newFixedThreadPool(10); // Max 10 threads.

然后在servlet服务期间(你可以忽略你不感兴趣的情况的结果):

Then during servlet's service (you could ignore the result for the case that you aren't interested):

Future<ReturnType> result = executor.submit(new CallableTask());

最后,在应用程序关闭或servlet的销毁期间:

Finally, during application's shutdown or servlet's destroy:

executor.shutdownNow(); // Returns list of undone tasks, for the case that.

这篇关于在Tomcat中从servlet生成线程的推荐方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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