java - 当我们可以使用ExecutorService时,为什么在EJB中使用@Asynchronous?

标签 java multithreading asynchronous jvm ejb

我对 Java 和 EJB 中的多线程也很陌生。我有一个场景,我必须使用线程同时访问 Web 服务。我有两种方法。

  1. 使用 ExecutorService 和 Callable 来同时访问服务。
  2. 使用EJB的@Asynchronous注解。

我读到的是:EJB 建议使用 @Asynchronous 而不是编写我们自己的线程实现。读完这篇文章后,我很困惑为什么 EJB 会这么说。因为 EJB 底层在 JVM 上工作,并且所有线程都将从 JVM 创建。那么为什么 EJB 限制我们使用它的 @Asynchronous 而不是我们的实现。

我在谷歌上搜索但没有找到满意的答案。如果有人知道EJB中线程创建和管理的细节请消除我的疑惑。

最佳答案

基本上可以在EJB 3.1 specification中找到答案:

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.

我想这个解释是不言而喻的。 Java EE 通常在应用程序服务器上的容器中实现,该规范旨在为容器提供有效完成其工作的最佳条件。

我能想到的另一个原因(我猜 Java EE 规范存在的原因之一)是它允许可重用​​性。可以这么说,没有必要重新发明轮子。

关于java - 当我们可以使用ExecutorService时,为什么在EJB中使用@Asynchronous?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39707360/

相关文章:

java - 线程中的异常 "main"java.sql.SQLException : Unable to open file

java - 如何使用JAVA查询标点符号敏感术语的Marklogic?

java - 为什么 Autowiring 在线程中不起作用?

c++ - 线程是否共享一些类字段?

javascript - Emberjs - 如何测试 promise 和其他异步行为?

java - 无法找到或加载主类 Swing Java

java - 这也是匿名派生类的例子吗? (Java 基础知识)

c# - 如何制定这个多线程编程场景?

javascript - 如何使用 Node require 调用导入的异步函数?

c# - await AsyncMethod() 与 await await Task.Factory.StartNew<TResult>(AsyncMethod)