Stateless beans have a much simpler existence. They’re born (created), they’re thrown into a pool with others of their kind, they run business methods for any client who asks, and they might eventually die. They aren’t passivated, they don’t keep client-specific state, and their creation and destruction (removal) aren’t tied to the whims of the client. Compare the difference between the lifecycle of a stateful vs. stateless bean:
The bean lifecycle (special moments in a bean’s life)
Stateful session beans
Bean creation (when the client wants a bean)
Bean use (when the client calls a business method)
Bean passivation (the bean is put to sleep to conserve resources)
Bean activation (the bean wakes up to service a business method from the client)
Bean removal (when the client is finished with the bean or the bean times out)
Stateless session beans
Bean creation (when the container wants to make a bean)
Bean use (when the client calls a business method)
Bean removal (when the container decides there are too many beans in the pool, or the bean throws a system exception.)
Comparing the lifecycles of stateful and stateless session beans
Stateful
Stateless
Client calls create on a stateless session bean home
Client calls create on the home.
Container makes the EJB object.
Container sends the client a stub to the EJB object.
Session bean creation is not related to the client
Container constructs the SessionContext object and the bean instance, then calls setSessionContext() on the bean.
Container puts the bean (which is now linked to its own context) in the pool for that bean type.
Client invokes a business method on her previously-acquired EJB object stub.
Container pulls a bean out of the pool and links it with the client’s EJB object.
Container invokes business method on the bean (1), the bean returns from the method (2), then Container sends bean back to the pool (3).
Object Interaction Diagram (OID) for bean creation
stateless session bean
Get Head First EJB now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.