既然可以使用ExecutorService,为什么还要在EJB中使用@Asynchronous?

Why use @Asynchronous in EJB when we can use ExecutorService?

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

  1. 使用 ExecutorService 和 Callable 并发命中服务。
  2. 使用EJB的@Asynchronous注解。

我读到的是:EJB 建议使用@Asynchronous 而不是编写我们自己的线程实现。阅读本文后,我对 EJB 为什么这么说感到困惑。因为 EJB 在 JVM 下工作,所有线程都将从 JVM 创建。那么为什么 EJB 限制我们使用它的 @Asynchronous 而不是我们的实现。

我在 google 上搜索过,但没有找到满意的答案。如果有人知道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 规范存在的原因之一是它允许可重用​​性。可以这么说,不需要重新发明轮子。

这里有更多信息

对于 EJB:

  1. 您需要一个具有 EJB 容器的应用程序服务器,以便它可以 运行 EJB(例如:Jboss 或 WebLogic)。
  2. EJB 之类的 Message Driven Beans (MDB) 可以监听队列(例如:Hornet Queue、RabbitMQ、IBM mq)等,并在 Queue.So 上丢弃消息时处理请求它是异步的。

  3. MDB的调用由容器控制,我们不需要写任何额外的代码。

执行器服务:

  1. 它由核心 java 提供,因此您不需要像 JBOSS 或 Weblogic 这样的应用程序服务器,您可以 运行 它作为您的独立系统的一部分 Java代码。
  2. 您需要编写一些代码,例如何时启动线程以及何时结束等,这是您使用 ExecutorService 实现的目标。

注意:根据您的要求,您的选项 1 对我来说似乎是正确的。 "Using ExecutorService with Callable to hit the service concurrently."