The Life Cycle of MDBs
Because MDB instances are stateless, their life cycles are simple and have two states: does not exist and ready. Figure 13-1 illustrates the life cycle of an MDB. An MDB instance begins its life when the container invokes three methods: newInstance(), setMessageDrivenContext(mdx), and ejbCreate(). Figure 13-2 illustrates this sequence. After invoking the ejbCreate() method, the MDB instance is in the ready pool, waiting to consume incoming messages. Because MDBs are stateless, all instances of MDBs in the pool are identical; they're allocated to process a message and then return back to the pool.
Figure 13-1 Life cycle of a message-driven bean instance
Figure 13-2 Sequence diagram of a message-driven bean initialization
The container can remove the instance of an MDB by invoking the ejbRemove() method, moving the MDB instance to the does not exist state. (See Figure 13-3 for an illustration.) When a message arrives, the container assigns the message to an MDB instance from the ready pool, which processes the messages by executing the onMessage(msg) method. After the message is processed, the MDB instance is returned to the ready pool. The pooling of message-driven bean instances enables the container to provide speed and scalability.
Figure 13-3 Sequence diagram of a message-driven bean removal