java - 无状态 session bean 中的多线程?

标签 java multithreading jakarta-ee ejb-3.0 ejb

EJB 3.0 规范不允许无状态 session bean 的业务方法创建新线程。这是为什么?创建仅执行原始计算且从不调用应用服务器的额外工作线程有什么问题?

比如说,我的 session bean 实现了一个让用户上传图像的服务,业务方法对这些图像进行 cpu 密集型图像处理。那么它只能使用一个cpu核心来完成这项工作,即使机器有8个或更多核心?如果我使用在内部创建工作线程的第三方图像处理库,我也会违反 EJB 规范,即使该库和这些线程与 EJB 容器完全无关。这似乎不对。

如果我忽略 EJB 规则并仍然创建一些工作线程来进行 CPU 密集型处理,会发生什么情况?当然,这些线程永远不会接触任何应用程序服务器对象,并且 bean 线程会在返回之前加入它们。还会有什么不好的事情发生吗?

最佳答案

The EJB 3.0 specification does not allow a business method of a stateless session bean to create new threads. Why is that?

简短版本:不允许从 EJB 管理线程,因为它会损害资源管理、事务管理、安全性(技术原因),也因为这是 EJB 模型不想提倡的东西(哲学原因)。

EJB 规范是这样说的:

21.1.2 Programming Restrictions

...

  • The enterprise bean must not attempt to manage threads. The enterprise bean must not attempt to start, stop, suspend, or resume a thread, or to change a thread’s priority or name. The enterprise bean must not attempt to manage thread groups.

These functions are reserved for the EJB container. Allowing the enterprise bean to manage threads would decrease the container’s ability to properly manage the runtime environment.

另见

(...) If i utilize a third party image processing library, that internally creates worker threads, i would also violate the EJB specs, even though that library and these threads have nothing to do with the EJB container at all. This does not seem right.

我能说什么,如果你不喜欢就不要使用 EJB。

What can happen if i ignore the EJB rules and still create some worker threads to do cpu intensive processing? Of course these threads will never touch any app server objects and the bean thread will join them before returning. Can still something bad happen?

这些线程是否接触应用服务器对象并不重要。规则就是规则,你不想遵守它们,你是自己的,行为是不确定的。有些容器可能更宽松并允许它,有些则不会,您的应用程序将不可移植,等等。但它仍然被明确禁止。

如果您想以标准方式“生成”线程,请使用 WorkManager API 或使用 JMS。

相关问题

关于java - 无状态 session bean 中的多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3816286/

相关文章:

xml - 实体已被引用但未声明

java - Java 中的枚举中是否有必要使用 toString() ?

ruby-on-rails - 如何捕获线程中的错误,然后在所有线程完成后重新抛出该错误?

java - 数字文字的自动装箱 : wrapper initialization vs passing method arguments inconsistency

multithreading - 我们真的需要运行所有这 1000 个线程吗?

C++11 线程卡在锁定互斥锁上

java - 这个连接池场景将如何实现?

java - jax-rs 检索表单参数

java - 与 Logstash 一起使用时在 log4j 上被阻止

java - 项目架构,在核心和服务之间传输数据