ejb3

EJB Life Cycle Example

1. The LifeCycle of EJB

The various stages through which an enterprise bean go through its lifetime is known as the life cycle of EJB. Each type of enterprise bean (stateful session, stateless session, singleton session, or message-driven) has a different lifecycle.

2. Life Cycle of a Stateful Session Bean

The following figure shows the life cycle of a stateful session bean. It has the following states:

  • Does not exist. In this state, the bean instance simply does not exist.
  • Ready state. A bean instance in the ready state is tied to particular client and engaged in a conversation.
  • Passive state. A bean instance in the passive state is passivated to conserve resource.

The various state transitions as well as the methods available during the various states are discussed below.

Life Cycle of a Stateful Session Bean
Life Cycle of a Stateful Session Bean

2.1 Moving from the Does Not Exist to the Ready State

When a client invokes a create method on a stateful session bean, the EJB container creates a new instance and invokes the callback method public void setSessionContext(SessionContext ctx). This method has the parameter javax.ejb.SessionContext, which contains a reference to the session context, that is, the interface to the EJB container, and can be used to self-reference the session bean object.

After the callback method setSessionContext is called, the EJB container calls the callback method ejbCreate that matches the signature of the create method.

2.2 The Ready State

A stateful bean instance in the ready state is tied to a particular client for the duration of their conversation. During this conversation the instance can the execute component methods invoked by the client.

2.3 Activation and Passivation

To more optimally manage resources, the EJB container might passivate an inactive stateful session bean instance by moving it from the ready state to the passive state. When a session bean instance is passivated, its (non-transient) data is serialized and written to disk, after which the bean instance is purged from memory. Just prior to serialization, the callback method ejbPassivate is invoked. If your session bean needs to execute some custom logic prior to passivation, you can implement it using this callback method.

If after passivation a client application continues the conversation by invoking a business method, the passivated bean instance is reactivated; its data stored on disk is used to restore the bean instance state. Right after the state has been restored, the callback method ejbActivateis invoked. If your session bean needs to execute some custom logic after activation, you can implement it using this callback method. The caller (a client application or another EJB) of the session bean instance will be unaware of passivation (and reactivation) having taken place.

If a stateful session bean is set up to use the NRU(not recently used) cache-type algorithm, the session bean can time out while in passivated state. When this happens, it moves to the does not exist state; that is, it is removed. Prior to removal the EJB container will call the callback method ejbRemove. If a stateful session bean is set up to use the LRU (least recently used) algorithm, it cannot time out while in passivated state. Instead this session bean is always moved from the ready state to the passivated state when it times out.

The exact timeout can be set using the idleTimeoutSeconds attribute on the @Session annotation. The cache-type algorithm can be set using the attribute on the same annotation.

2.4 Moving from the Ready to the Does Not Exist State

When a client application invokes a remove method on the stateful session bean, it terminates the conversation and tells the EJB container to remove the instance. Just prior to deleting the instance, the EJB container will call the callback method ejbRemove. If your session bean needs to execute some custom logic prior to deletion, you can implement it using this callback method.

An inactive stateful session bean that is set up to use the NRU (not recently used) cache-type algorithm can time out, which moves it to the does not exist state, that is, it is removed. Prior to removal the EJB container
will call the callback method ejbRemove. If a stateful session bean set up to use the LRU (least recently used) algorithm times out, it always moves to the passivated state, and is not removed.

The exact timeout can be set using the idleTimeoutSeconds attribute on the @Session annotation. The cache-type algorithm can be set using the cacheType attribute on the same annotation.

3. The Lifecycle of a Stateless Session Bean

The following figure shows the life cycle of a stateless session bean. A stateless session bean has two states:

Does not exist. In this state, the bean instance simply does not exist.
Ready state. When WebLogic Server is first started, several bean instances are created and placed in the Ready pool. More instances might be created by the container as needed by the EJB container.

The various state transitions as well as the methods available during the various states are discussed below.

SLSBLifeCycle1
Life Cycle of a Stateless Session Bean

3.1 Moving from the Does Not Exist to the Ready State

When the EJB container creates a stateless session bean instance to be placed in the ready pool, it calls the callback method public void setSessionContext(SessionContext ctx). This method has the parameter javax.ejb.SessionContext, which contains a reference to the session context, that is, the interface to the EJB container, and can be used to self-reference the session bean object.

After the callback method setSessionContext is called, the EJB container calls the callback method ejbCreate. You can implement this callback method to, for instance, obtain the home interfaces of other EJBs invoked by the session bean, as shown in Defining a Session Bean. The ejbCreate method is only called once during the lifetime of a session bean, and is not tied to the calling of the create method by a client application. For a stateless session bean, calling the create method returns a reference to a bean instance already in the ready pool; it does not create a new bean instance. The management of stateless session bean instances is fully done by the EJB container.

3.2 Ready State

When a bean instance is in the ready state, it can service client requests; that is, execute component methods. When a client invokes a business method, the EJB container assigns an available bean instance to execute the business method. Once execution has finished, the session bean instance is ready to execute another business method.

3.3 Moving from the Ready to the Does Not Exist State

When the EJB container decides to reduce the number of session bean instances in the ready pool, it makes the bean instance ready for garbage collection. Just prior to doing this, it calls the callback method ejbRemove. If your session bean needs to execute some cleanup action prior to garbage collection, you can implement it using this callback method. The callback method is not tied to the remove method invoked by a client. For a stateless session bean, calling the remove method invalidates the reference to the bean instance already in the ready pool, but it does not move a bean instance from the ready to the does not exist state, as the management of stateless session bean instances is fully done by the EJB container.

4. The Lifecycle of a Singleton Session Bean

A singleton session bean is never passivated and has only two stages, non existent and ready for the invocation of business methods

Lifecycle of a Singleton Session Bean
Lifecycle of a Singleton Session Bean

The EJB container typically creates and maintains a pool of stateless session beans, beginning the stateless session bean’s lifecycle. The container performs any dependency injection and then invokes the method annotated @PostConstruct, if it exists. The bean is now ready to have its business methods invoked by a client.

At the end of the lifecycle, the EJB container calls the method annotated @PreDestroy, if it exists. The bean’s instance is then ready for garbage collection.

5. The Lifecycle of Message-Driven Bean

Lifecycle of a Message-Driven Bean
Lifecycle of a Message-Driven Bean

The EJB container usually creates a pool of message-driven bean instances. For each instance, the EJB container performs these tasks. If the message-driven bean uses dependency injection, the container injects these references before instantiating the instance.The container calls the method annotated @PostConstruct, if any.

Like a stateless session bean, a message-driven bean is never passivated and has only two states: nonexistent and ready to receive messages. At the end of the lifecycle, the container calls the method annotated @PreDestroy, if any. The bean’s instance is then ready for garbage collection.

This type of bean follow three steps:

  1. setMessageDrivenContext: This method is used to pass the context object to the instance.
  2. ejbCreate: This method is generated automatically whenever a new enterprise bean is created.
  3. ejbRemove: At this stage the bean instance is ready to move for the garbage collection.
  • em.persist(newsEntity): This method makes an entity instance that is managed and persistence.
  • em.merge(newsEntity): By using this method we can merge the state of the given entity into the current persistence context.
  • em.remove(em.merge(newsEntity)): This method is used for removing the entity instance.

Here is the program denoting life cycle of message driven bean:

package ejb;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class NewsEntityFacade implements NewsEntityFacadeLocal {
@PersistenceContext
private EntityManager em;

public void create(NewsEntity newsEntity) {
em.persist(newsEntity);
}

public void edit(NewsEntity newsEntity) {
em.merge(newsEntity);
}

public void remove(NewsEntity newsEntity) {
em.remove(em.merge(newsEntity));
}
}

6. Conclusion

In this tutorial, we learn about various stages through which an enterprise bean go through its lifetime. For more information on EJB technology, see http://www.oracle.com/technetwork/java/ejb-141389.html.

Dhruv Gupta

Dhruv holds Master degree in MCA and is OCPJP Certified Java EE Developer. He has been involved the wide variety of business application. Particularly always involved in J2EE technology and business domain as Finance. His areas of interest include Java EE, scalable architecture, object oriented design and In-Memory data grids. He loves writing about and evangelizing Java EE technologies. He is working as a software engineer in Finance domain where he is involved in projects based on Java J2EE technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
M Chisty
M Chisty
6 years ago

Did not understand the text/grammar here: “During this conversation the instance can the execute component methods invoked by the client.”

Can you please edit or clarify this line?

Back to top button