About Message-Driven Beans

See Also

A message-driven bean is an enterprise bean that enables J2EE 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 J2EE component: an application client, another enterprise bean, or a web component.

Why Use Message-Driven Beans?

You might use message-driven beans instead of session beans or entity beans if you want to avoid tying up server resources. Session beans and entity beans also enable you to send and receive JMS messages, but they operate synchronously, not asynchronously, as do message-driven beans.

Comparison to Session Beans and Entity Beans

Unlike session beans and entity beans, clients of message-driven beans do not access them through interfaces. 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