O'Reilly logo

Head First EJB by Bert Bates, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Compared to stateful beans, stateless beans have a simple life

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

image with no caption

Stateless

image with no caption

Client calls create on a stateless session bean home

  1. Client calls create on the home.

    image with no caption
  2. Container makes the EJB object.

    image with no caption
  3. Container sends the client a stub to the EJB object.

    image with no caption

Session bean creation is not related to the client

  1. Container constructs the SessionContext object and the bean instance, then calls setSessionContext() on the bean.

    image with no caption
  2. Container puts the bean (which is now linked to its own context) in the pool for that bean type.

    image with no caption

Business method call

  1. Client invokes a business method on her previously-acquired EJB object stub.

    image with no caption
  2. Container pulls a bean out of the pool and links it with the client’s EJB object.

    image with no caption
  3. Container invokes business method on the bean (1), the bean returns from the method (2), then Container sends bean back to the pool (3).

    image with no caption

Object Interaction Diagram (OID) for bean creation

stateless session bean

image with no caption
image with no caption

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required