About Message-Driven Beans

See Also

A message-driven bean is an enterprise session bean that enables Java EE applications to process messages asynchronously. The bean acts as a Java Message Service (JMS) message listener, which is similar to an event listener except that the message-driven bean receives messages instead of events. The messages can be sent by any Java EE component: an application client, another enterprise bean, or a web component.

Why Use Message-Driven Beans?

Message-Driven Beans are the solution to build asynchronous enterprise applications where processing starts up when a message comes in. This approach enables a loose coupling between your enterprise application modules. A sender (aka producer) sends a message to a JMS managed object (topic or queue) to initiate a process.

Comparison to Session Beans

Unlike session beans, clients of message-driven beans do not access them directly. A message-driven bean has only a bean class.

In several respects, a message-driven bean resembles a stateless session bean:

The instance variables of the message-driven bean instance can maintain some state information across the handling of client messages, such as an object reference to an enterprise bean object.

Message Handling

When a message arrives, the container calls the message-driven bean's onMessage method to process the message. The onMessage method normally casts the message to one of the five JMS message types and handles the message in accordance with the application's business logic. The onMessage method might call helper methods, or it might invoke a session bean or an entity bean to process the information in the message and possibly store the results in a database.

Many instances of a message-driven bean class can execute concurrently, enabling a stream of messages to be processed concurrently. Because there are no guarantees of the exact order in which messages are delivered to these instances, message-driven beans must be prepared to handle messages that are out of sequence. For example, the message to cancel a reservation might be delivered before the message to make the reservation.

Transactions

The container provides the message-driven bean instance with a MessageDrivenContext, which gives the bean instance access to the context maintained for it by the container. Depending on whether the bean manages its own transactions or relies on the container's transaction management, the bean can access different methods of MessageDrivenContext to handle transactions.

See Also
Sending a JMS Message
About Entity Beans
About Session Beans
Creating an Enterprise Bean
About Business Methods

Legal Notices