Prev | Next

TOC | Index

J2EETM Developer's Guide
Session Beans


State Management Modes

When you specify the deployment descriptor of a session bean, you must choose between two state management modes: stateful or stateless.

Stateful Session Beans

The CartEJB example (see "Session Bean Class") has three instance variables: customerName, customerId, and contents. These variables represent the conversational state of the shopping cart application. Because the CartEJB contains a conversational state, it is called a stateful session bean.

The state is retained for the duration of the client-bean session. When the client removes the bean, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean is over there is no need to retain the state.

Stateless Session Beans

A stateless session bean does not maintain a conversational state for a particular client. When a client invokes the method of a stateless bean, the beans's instance variables may contain a state, but only for the duration of the invocation. When the method is finished, the state is no longer retained. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client.

Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.

At times, the EJB container may write a stateful session bean out to secondary storage. However, stateless session beans are never written out to secondary storage. Therefore, stateless beans may offer better performance than stateful beans.

The home interface of a stateless session bean must have a single create method with no arguments. The session bean class must contain one ejbCreate method, also without arguments. (The arguments are only needed by stateful session beans, which use them to initialize their states.)

Choosing Between Stateful and Stateless Session Beans

You should consider using a stateful session bean if any of the following conditions are true:

Since the primary goal of a session bean is to represent a client in the J2EE server, most of your session beans will be stateful. However, sometimes you may want to use stateless session beans:



Prev | Next

TOC | Index


Copyright © 2000 Sun Microsystems, Inc. All rights reserved.