Enterprise JavaBeans (EJB) are the workhorses of a Java 2 Enterprise Edition application, toiling in the layer between back-end systems and the presentation layer. Of the three types of EJBs—Session, Entity, and Message Driven—Session Beans are especially apt in this role. Within the EJB framework, the Session Bean encapsulates task or process-oriented behavior (you can read an introduction to EJBs in my previous article).
Something about sessions
Thinking of Session Beans as representing tasks, and not persistent data, makes understanding when and why to use them a simple proposition. For instance, a Session Bean would perform the search for a user in a database, but not represent the user as a persistent business object. Session Beans may communicate with all other types of beans—their abilities extend well beyond database transactions. Distributing application work in this manner (known as a facade pattern) is ideally suited for Session Beans’ operational nature.
All Session Beans derive from the javax.ejb.SessionBean class. True to their name, Session Beans exist only for a single client session. The client may be a Java Servlet, a desktop application, another EJB, or any other way of trading information with the bean. The life cycle of a Session Bean begins on first contact by the client and terminates when the client explicitly destroys the bean by calling the remove() method of the EJB home interface, which in turn calls the ejbRemove() method of the bean. A session also ends when a preset amount of time, determined by the EJB container, passes. In the interest of server resources, developers may want to avoid dealing with the "timeout" setting and seal the fate of the bean themselves when coding the client. Developers should also watch for Session Bean transience when an EJB Container restarts; clients may regain a reference to the same type of bean, but most likely not the exact same bean.
A bean without a state
Session Beans can be stateless or stateful, displaying different behavior based on this criteria. The concept of state according to a Session Bean is similar to that in an HTTP setting; interaction between client and server—in this case, the bean itself—takes place within a defined context. A Stateful Session Bean holds information about both client and bean across multiple method calls. A Stateful Session Bean communicates with only one client, whereas an instance of a stateless session bean may communicate with several clients simultaneously. Listing A provides an example of a Stateless Session Bean. Clients might use this bean in code such as that found in Listing B.
Brief interlude: ejb-jar.xml
Determining the stateless or stateful nature of a bean occurs when deploying the bean to the container via the bean’s deployment descriptor, called ejb-jar.xml. The deployment descriptor for the Stateless Session Bean above might look like Listing C. Easily modifying one line makes this a Stateful Bean:
This difference also lets the container manage resources effectively. After a session ends for a Stateless Bean, the container returns the bean to a resource pool. As clients require these beans, the container provides instances from the pool. If requests outnumber available beans, the container creates more instances; if no clients need beans, the container may destroy instances in the pool. Created on an as-needed basis, Stateful Beans enter the one-to-one relationship described earlier.
If a Stateful Bean falls out of use by the client, the container stores the state of the bean, usually by writing the information to disk.
Of course, developers need to implement some additional code to make a Stateful Bean useful. The code in Listing D augments the previous example with state-persistent data members and methods. The client uses this bean in a slightly different manner. The database, accessed by a facade pattern session bean, loads the customer-specific HashMap in the Stateful Bean via the setMessages() method. This makes the HashMap state-persistent, storing only messages relevant to the identified customer. In practice, the client might look like Listing E.
A notable addition in a Stateful Bean: that of a create() method taking an argument. The argument helps identify the proper bean and its associated state. Also, a Stateful Session Bean relies more on the ejbActivate() and ejbPassivate() methods, allowing the container to activate (or deactivate) the proper instance of a bean. Developers may use these methods for routine maintenance, such as closing database connections. Even though a degree of persistence comes with Stateful Session Beans, the container destroys unused references after a period of time, or if the container restarts. This is in contrast to Entity Beans, examined in an upcoming article, whose information remains after the timeout period or restart occurs.
Download the code
You can download MessageManagerBean.java, ejb-jar.xml, and MessageManagerStateBean.java here.
Consider this session over
By representing tasks or actions within a J2EE application, Session Beans handle numerous situations, especially when used in conjunction with other EJBs. Understanding the transient nature of Session Beans provides invaluable assistance to developers. The nuances of Stateless and Stateful Beans become just as important to leveraging their behaviors properly. With these concepts in hand, properly designed and implemented Session Beans enhance the functionality and efficiency of EJB applications.