# Getting Started with Message-Driven Beans

This topic provides an overview of message-driven bean development. It contains the following sections:

- What Are Message-Driven Beans?
- Asynchronous and Concurrent Processing
- Topics and Queues
- The Life Cycle of a Message-Driven Bean

##
What are Message-Driven Beans?

Message-driven beans are server-side objects used only to process JMS messages. These beans are stateless, in that each method invocation is independent from the next. Unlike session and entity beans, message-driven beans are not invoked by other beans or client applications. Instead a message-driven bean responds to a JMS message.

Because message-driven beans are not invoked by other EJBs or clients, these beans do not have interfaces. For each message-driven bean a single method, onMessage, is defined to process a JMS message. Although message-driven beans cannot be invoked by other EJBs, they can in turn invoke other EJBs. Also, message-driven beans can send JMS messages. As with the other types of EJBs, the EJB container is responsible for managing the beans environment, including making enough instances available for processing and message-acknowledgement.

## Asynchronous and Concurrent Processing

A core feature of message-driven beans is the notion of asynchronous processing. A client application can send a JMS message to execute a certain business task. After the message has been sent, the client application can continue right away and does not have to wait for the JMS message to be received and processed. This is especially helpful when the business task is complex, requires the use of entity (and session) beans, and takes a long time to complete. In contrast, if the same client application were to use a session bean to execute a certain business task, it would have to wait until the session bean method completed and returned control to the client application. The message façade design pattern formalizes this use of message-driven beans as an intermediary between client applications and entity beans to achieve asynchrony. An example of this pattern is shown in the Message-Driven Bean Sample.

Another important feature of message-driven beans is that JMS messages are processed concurrently. That is, although each bean instance handles a message at a time, the EJB container takes care of creating enough bean instances to handle the message load at a given moment. In WebLogic you can set the initial number and max number of bean instances created by the container. For more information, see the @ejbgen:message-driven Annotation.

Because message-driven beans are stateless and processing of JMS messages occurs in an asynchronous message, there is no guarantee that messages are processed in the order they were sent. Therefore, sending multiple messages such that one message is dependent on the successful processing of another message might cause unexpected results. Instead, you should reconsider the granularity of your business task such that one message can initiate its execution, possibly by handling one piece of the task, and then sending a JMS message to be processed by another message-driven bean for the remainder of the business task.

## Topics and Queues

A message-driven bean listens to a particular channel for JMS messages. There are two types of channels, namely topics and queues. Topics implement the publish-and-subscribe messaging model, in which a given message can be received by many different subscribers, that is, many different message-driven bean classes (not instances) listening to the same topic. In contrast, queues implement the point-to-point messaging model, in which a given message is received by exactly one message-driven bean class, even when multiple classes are listening to this queue.

## The Life Cycle of a Message-Driven Bean

The EJB container is responsible for creating a pool of message-driven bean instances. When it creates an instance, it calls the setMessageDrivenContext() and the ejbCreate() methods. At this point the message-driven bean is ready to receive messages. When a bean instance is processing a JMS message, its onMessage method is being invoked. When the EJB container removes a bean instance, it first calls the ejbRemove method before the instance is ready for garbage collection. The life cycle of a message-driven bean is depicted in the following figure.

When defining a message-driven bean in WebLogic, in most cases you will implement the onMessage method to execute a particular business task, and use the ejbCreate method to implement actions that only need to be executed once, such as looking up the home interfaces of entity beans that are invoked by the message-driven bean's onMessage method. A typical example of simple message-driven bean is given below. Notice that the ejbCreate method is used to find the home interface of a Recording entity bean, while the onMessage method processes the message and invokes the Recording bean:

    /**
     * @ejbgen:message-driven
     *   ejb-name = Statistics
     *   destination-jndi-name="jms.EJBTutorialSampleJmsQ"
     *   destination-type = javax.jms.Queue
     *
     * @ejbgen:ejb-local-ref
     * type="Entity"
     * name="ejb/recordLink"
     * local="bands.Recording"
     * link="Recording"
     * home="bands.RecordingHome"
     */
    public class StatisticsBean extends GenericMessageDrivenBean implements MessageDrivenBean, MessageListener
    {
      private RecordingHome recordingHome;

      public void ejbCreate() {
        try {
            javax.naming.Context ic = new InitialContext();
            recordingHome = (RecordingHome)ic.lookup("java:/comp/env/ejb/recordLink");
        }
        catch(NamingException ne) {
            System.out.println("Encountered the following naming exception: " + ne.getMessage());
        }
      }

      public void onMessage(Message msg) {
         try {
             // read the message
             MapMessage recordingMsg = (MapMessage)msg;
             String bandName = recordingMsg.getString("bandName");
             String recordingTitle = recordingMsg.getString("recordingTitle");
             ...
             // save the rating with the recording
             Recording album = recordingHome.findByPrimaryKey(new RecordingBeanPK(bandName, recordingTitle));
             album.setRating(rating);
         }
         catch(Exception e) {
            System.out.println("Encountered the following exception: " + e.getMessage());
         }
      }
    }

You can implement the ejbRemove method if cleanup is required before the object is removed, and you can implement setMessageDrivenContext method if you need access to the javax.ejb.MessageDrivenContext provided by the EJB container. The MessageDrivenContext contains information about the container, in particular its transaction methods; for more information, see your favorite J2EE documentation. A message-driven bean defined in WebLogic by default extends weblogic.ejb.GenericMessageDrivenBean, which provides empty definitions for all these methods with the exception of the onMessage method; the definition of your bean must therefore implement the onMessage method.

Related Topics

Message-Driven Bean Sample