Message Driven Bean
A message-driven bean (MDB) is an enterprise bean that allows Java EE applications to process messages asynchronously. In other words, an MDB is an asynchronous message consumer.
A message-driven bean is invoked by the container as a result of the arrival of a message at the destination or endpoint that is serviced by the message-driven bean.
The messages can be sent by any Java EE component (an application client, another enterprise bean, or a web component) or by a JMS application or system that does not use Java EE technology.
A message-driven bean instance is created by the container to handle the processing of the messages for which the message-driven bean is the consumer. Its lifetime is controlled by the container.
When a message arrives, the container calls the message-driven bean’s onMessage(Message message) method to process the message. The onMessage() method normally casts the message to one of the five JMS message types and handles it in accordance with the application’s business logic. The onMessage() method can call helper methods or can invoke a session bean to process the information in the message or to store it in a database.
MDB Characteristics
Message-driven beans have the following characteristics.
- They execute upon receipt of a single client message.
- They are invoked asynchronously.
- They are relatively short-lived.
- They do not represent directly shared data in the database, but they can access and update this data.
- They can be transaction-aware.
- They are stateless.
MDB vs. Stateless Session Bean
A message-driven bean resembles a stateless session bean in many ways:
- Message-driven bean instances have no conversational state. This means that all bean instances are equivalent when they are not involved in servicing a client message.
- The container can pool these instances to allow streams of messages to be processed concurrently.
- A single message-driven bean can process messages from multiple clients.