在servlet容器中创建新线程时,最佳实践是什么?

发布于 2025-01-26 11:46:19 字数 321 浏览 4 评论 0 原文

今天,我正在查看一些使用 opecutors.newsinglethreadscheduledexecutor()的Web应用程序代码,以对最终状态进行轮询REST API(Think Code 完整,失败等)。知道servlet容器已经是一个高度并发的环境,它担心我每个请求线程都在创建另一个线程。

我已经考虑创建一个固定尺寸的线程池,但是我不确定是否必须以servlet容器的特定方式对其进行管理。我不确定如何决定最佳尺寸。我也不完全相信这是正确的行动方案。

我想确认这确实是危险的,说明了为什么并理解出色的解决方案的外观。

Today I was looking at some web app code that used Executors.newSingleThreadScheduledExecutor() on a per request basis to poll a REST API for a final status (think COMPLETE, FAILED, etc.). Knowing that a servlet container is already a highly concurrent environment, it worried me each request thread was creating another thread.

I have looked at creating a fixed sized thread pool but I'm not certain if it has to be managed in a servlet container specific way. I'm unsure how to decide on an optimal size. I'm also not completely confident that this is the right course of action.

I'd like to confirm that this indeed is dangerous with of an explanation of why and understand what a superior solution might look like.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你如我软肋 2025-02-02 11:46:19

Servlet asynccontext.start(runnable)是首选的方法,如果您想与运行> Runnable 中的servlet API进行交互(这将在Servlet容器的线程中运行池并允许容器管理线程周围的各种上下文,例如classloaders,Security,CDI,会话等)。

asynccontext 方法的唯一缺点是,您正在消耗servlet容器线程来进行处理。如果您还使用servlet async i/o,那么您已经以宏伟的方式抵消了这一负面,实际上您的扩展能力可以显着提高。

如果您不需要从运行中与Servlet API进行交互,请与您从Java 执行者获得的线程池执行的简单线程一起使用。

The servlet AsyncContext.start(Runnable) is the preferred way if you want to interact with the Servlet API and contexts from within your Runnable (this will run within the Servlet Container's Thread Pool and allow the container to manage the various contexts around your thread, like classloaders, security, cdi, sessions, etc).

The ONLY downside with the AsyncContext approach is that you are consuming Servlet Container threads to do your processing. If you also use Servlet Async I/O, then you've offset this negative in a grand way, and you'll actually have a noticeable improvement in your ability to scale.

If you have no requirement to interact with the Servlet API from your Runnable, then go with simple threads executed from a Thread Pool you have obtained from the Java Executors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文