今天,我正在查看一些使用 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.
发布评论
评论(1)
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 yourRunnable
(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 JavaExecutors
.