Getting Started with Enterprise JavaBeans™


Session Beans

Tutorial Home Section Home Previous Next



Stateful Session Beans

     Stateful session beans are assigned to a specific client and are able to retain session state across multiple requests from that client for the duration of the bean's lifetime. Because of the link to the client and the need to retain state, stateful session beans are not as scalable as the stateless variety, although the container can still use pooling techniques. When deciding whether to use stateless or stateful session beans, you should consider the importance to your application of maintaining state externally, as opposed to maintaining state in the client.

     Other than the required life cycle methods, stateful session beans will look very similar to standard Java objects with instance variables. A public, no-arg constructor is required. There are three milestones in a stateful session bean's life cycle: Does Not Exist, Ready, and Passive. To place a session bean in the Ready state, the container:

     There may be multiple ejbCreate() methods with differing input arguments, just as an ordinary Java class might have multiple constructors.

     Prior to placing a bean in the Passive state, the container invokes ejbPassivate(). Before placing the bean back in the Ready state, the container calls ejbActivate().

     When the container no longer requires the bean, it calls the bean's ejbRemove() method. After this operation, the bean is effectively destroyed and back to the Does Not Exist state.

     A container may use passivation to enhance scalability. While stateless session beans are relatively easy to pool, stateful session beans must appear to be linked to a single client and maintain state with that client. One way to accomplish a semblance of pooling is to use something similar to context switching in an operating system's application management environment. Serialization/deserialization is most commonly employed to save/restore bean state to and from secondary storage. When the container decides the time is appropriate, it will invoke ejbPassivate() just before serialization and ejbActivate() just after deserialization. The bean should be prepared to release or reacquire, respectively, resources that are not suitable for serialization (such as a database connection) when these methods are called. If there are no serialization, performance, or efficiency implications, the bean may choose to do nothing at these times. Clearly, any acquired resources should also be released on an ejbRemove() invocation.

Tutorial Home Section Home Previous Next