wo major limitations in the Enterprise JavaBeans (EJB) specification make it difficult to develop multi-threaded EJB applications:
- New user threads cannot be created inside EJB Container.
- EJB methods cannot be called asynchronously.
These restrictions make it difficult to develop concurrent applications with EJB. Luckily, by utilizing JMS along with EJB within your applications, you can achieve concurrency. JMS's asynchronous model and its support for the MessageDrivenBean (MDB) can be applied as a mechanism for a client to use EJB asynchronously.
The Need for Concurrency in EJB
Concurrent processing in EJB is a necessity for various applications. For example, say you have a database containing various commodity prices. Each commodity has more than one price, so you want to identify the minimum price. Assume that identifying a minimum price requires exhaustive calculations, which are implemented by a SessionBean. The SessionBean has a method that accepts a commodity and finds its minimum price.
Now consider a client that has a set of commodities and wants to find a minimum price for each. The client can call the SessionBean by passing one commodity at a time to find its minimum price; in which case it has to call the SessionBean serially for each commodity. Due to the restrictions in EJB, you cannot create threads within the SessionBean that will allow it to accept the commodity in a new thread and return the control back to the client, enabling it to send the next commodity. The only alternative for the client is to create multiple threads outside the SessionBean, so that each thread can call the SessionBean concurrently to find the minimum price for the Commodities. This approach forces the client to manage the threads, which is extra work.
To avoid creating multiple threads in the client, you can use JMS to send each commodity asynchronously for processing in the SessionBean. The JMS approach is also useful when communication between the client and the SessionBean is unreliable, or when the client and the SessionBean are distributed on a heterogeneous platform.