|Lesson 6||Stateful and Stateless Session Beans|
|Objective|| Describe the difference between stateful and stateless session beans.|
Stateful and Stateless Session Beans
Stateful session beans
Normally, session beans are stateful, with the container making sure the bean object never loses its state.
When a client requests the container to create a session bean instance on its behalf,
it usually passes the instance the appropriate information that the session bean uses to set its initial state.
The client assumes that the bean object, once created, will always be available with the state maintained.
Even if the container needs to temporarily store the bean instance on secondary storage, it must makes sure its state is restored when it is read back in.
Stateful session bean example: the shopping cart
An example of a session bean is a shopping cart. The shopping cart instance has a one-to-one relationship with the shopper who is the client;
it can be discarded when the client completes the purchase of the shopping cart contents and it is emptied. Its state is the current contents.
If the client has forgotten his wallet, then the store can move the shopping cart off to one side while the shopper drives home to get it.
When he returns to the store, the shopping cart can be retrieved and the purchase completed. If the store catches fire (equivalent to the container crashing) while shopping, the shopper can
abandon the cart and will return to shop when the store is back in operation.
The state of a stateful session bean instance lasts until the bean instance is removed.
If the bean instance's state needs to be saved for later use by another bean, it must be stored in some persistent store before removal.
The new session bean instance will have to initialize itself from the persistent store when it is created.
Stateless session beans
Stateless session beans, as their name suggests, have no state held on behalf of the client and only need to exist for the duration of a single method call.
The container can pool multiple bean instances and grab the most convenient one when a client needs it. The container can manage stateless session beans very efficiently.
Stateless: The property of an object such that it contains no information that needs to be preserved across method calls.
Stateless session bean example: the currency converter
An example of a stateless bean is a currency converter. Give it a value in a certain currency and it will convert it to the equivalent
value in US dollars. It does not maintain a state, for the client, across method calls. However, it does have a private state, the conversion rates; however, that state is general to all clients.
In the next lesson, entity beans will be introduced.