1

I am new to multithreading in Java and EJB too. I have a scenario where I have to hit a web service concurrently using threads. I have got two approaches for that.

  1. Using ExecutorService with Callable to hit the service concurrently.
  2. Using @Asynchronous annotation of EJB.

What I have read is: EJB recommends to use @Asynchronous over writing our own threaded implementation. After reading this I am confused about why EJB says so. Because underneath EJB works on JVM and all threads will be created from JVM. So why EJB restricts us on using it's @Asynchronous rather than our implementation.

I searched on google but did not found any satisfactory answer. If anyone knows the details of thread creation and management in EJB please clear my doubts.

Anant666
  • 416
  • 9
  • 26

2 Answers2

1

Basically, the answer can be found in the 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.

I guess the explanation speaks for itself. Java EE is typically implemented in a container on an application server, and the specification has been designed to give the container the best conditions to effeciently do its job.

Another reason I can think of, and I guess one of the reasons the Java EE specification exists at all, is that it allows for reusability. There is no need to reinvent the wheel, so to speak.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Magnilex
  • 11,584
  • 9
  • 62
  • 84
0

Here is some more info

For EJB:

  1. You need an application server which has EJB container so that it can run EJB's (Eg: Jboss or WebLogic).
  2. EJB's like Message Driven Beans (MDB) can listen to Queues (Eg: Hornet Queue, RabbitMQ, IBM mq) etc and process the request when the message is dropped on the Queue.So its Asynchronous.

  3. The invoking of MDB is controlled by the container and we dont need to write any code Extra code.

ExecutorService:

  1. Its provided by core java so you don't need a application server like JBOSS or Weblogic you can run it as part of your stand alone Java code.
  2. You need to write some code as when to start the threads and when to end etc which is what your are achieving using ExecutorService.

NOTE: Based on your requirement your option 1 seems right to me. "Using ExecutorService with Callable to hit the service concurrently."

Reddymails
  • 793
  • 1
  • 10
  • 24