State: Stateful maintains information across sessions while stateless doesn’t. If a transaction would span over two or more bean executions you should use stateful session bean, otherwise use stateless session bean. Stateful beans remember state between

Scalability: Stateful beans hurt scalability.

Pooling: Stateless beans, by nature, need not know their clients once the remote business method returns. These beans can therefore be bean-pooled. On the other hand stateful session beans may be requested back(with previous state) by a client using the javax.ejb.Handle reference that the client may have retained. In this case, the bean will need to be re-instated entirely. These beans therefore can only be instance-pooled and never shared between clients.

Passivation: Stateless beans are not passivated. SFSB’s are activated/passivated.

Version 2.X:

In ejb-jar.xml ‘session-type’ attribute determines whether the bean is stateful or stateless.

Stateful Session EJB is a server-side object designed to hold data on behalf of a particular client.

SFSBs should be used to store session-oriented data. They hold the data on behalf of the client. Session-oriented data is used to track a multi-request sequence, ordering, or any associated data that is part of a sequence.

SFSBs, however, have a limited lifespan and are not intended to survive server crashes. Although SFSBs are allowed to access a database and load data into memory, but the act of caching persistent data lies within the responsibilities of entity beans.

The EJB specification suggests that a shopping cart for an e-commerce system could be implemented with SFSBs. This is perfectly acceptable if that shopping cart is only intended to be an in-memory implementation that does not need to survive a server crash. In reality, however, most implementations of shopping carts are required to survive server crashes; the data contained within the shopping cart needs to be persistent and transactional — with an in-memory data cache. i:e Using entity beans.

When to use them ?

In very few J2EE systems !!

Systems that have JSP/servlet front-ends should use HttpSession objects to store session-oriented state. Using both HttpSession and SFSB is simply duplicating the effort.

For systems that do not have a servlet/JSP front-end, SFSBs should be used to track session-oriented state similar to the way a web-based system would use an HttpSession object.

Use SFSB’s along with HttpSession when:

Your app server doesn’t offer caching of HttpSession objects. This will mean that you may have to have to limit on number of sessions. Using SFSB’s in this scenario will increase scalability as a container can activate/passivate SFSB’s as needed.