Distributed Objects   «Prev  Next» 

Lesson 6Stateful and Stateless Session Beans
Objective Describe the difference between stateful and stateless session beans.

Stateful and Stateless Session Beans

In Java EE (Enterprise Edition), session beans are components used to implement business logic in enterprise applications. They can be classified into two categories: stateful and stateless session beans. The key difference between them lies in how they manage state.
  1. Stateless Session Beans:
    "Stateless session beans" do not maintain any client-specific state between method invocations. Each time a client invokes a method on a stateless session bean, it may get a different instance of the bean from a pool, as no client-specific data is stored in the bean itself. These beans are typically used for operations that are independent of previous method calls, such as performing calculations, sending notifications, or processing data.
    Characteristics:
    • No Client State: Stateless session beans do not store any state related to a specific client between method invocations.
    • Pooled Instances: The container can pool instances of stateless beans and reuse them across multiple clients. This improves scalability, as fewer bean instances are needed.
    • Short Lifespan: The lifecycle of a stateless session bean is short-lived, often tied to individual method calls.
    • Use Case: Commonly used for tasks like transaction processing, calculations, or any other service that does not depend on previous interactions with the client.

    Example Use Case: A stateless session bean might be used to validate a credit card number or perform a stateless operation like tax calculation, where the same logic can be applied to different clients without tracking individual client data.
  2. Stateful Session Beans: "Stateful session beans" maintain state between method invocations, meaning that they retain data for a specific client across multiple requests. This state is typically stored in instance variables, and it is unique to each client. Stateful beans are useful when the interactions with the client require maintaining conversational state, such as managing a shopping cart in an e-commerce application.
    Characteristics:
    • Client-Specific State: Stateful session beans maintain the state of a specific client session across multiple method calls. The state is typically stored in instance variables.
    • Dedicated to One Client: A stateful session bean is dedicated to a single client for the duration of the conversation, which means that it cannot be shared among clients.
    • Longer Lifespan: These beans live longer than stateless session beans, often lasting for the duration of the client session.
    • Passivation: When not actively in use, the container can "passivate" (serialize) a stateful session bean to free up resources, then "activate" it again when needed.
    • Use Case: Used for operations that require maintaining a conversational state with the client, such as a sequence of operations in a multi-step workflow (e.g., online shopping, banking transactions).



Example Use Case: A stateful session bean might be used in a shopping cart application where the items added to the cart by a client need to be retained across multiple interactions with the server.
Comparison Summary:
Feature Stateless Session Bean Stateful Session Bean
Client-Specific State Does not maintain client-specific state Maintains client-specific state
Instance Reuse Instances are pooled and shared Each client gets a dedicated instance
Lifespan Short-lived (per method invocation) Long-lived (per client session)
Scalability More scalable due to instance pooling Less scalable due to dedicated instances
Use Case Independent operations (e.g., services, calculations) Conversational operations (e.g., shopping cart, banking)

Conclusion: The choice between stateful and stateless session beans depends on the nature of the business logic. Stateless session beans are more efficient and scalable for independent operations, while stateful session beans are useful when you need to maintain a client's state across multiple interactions.


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 it 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.

Modern Alternative for implementing Server Side Shopping Cart in Java

In Jakarta EE 10, the modern alternative to a stateful session bean-based shopping cart (from the dotcom-era J2EE days) can be implemented using several updated technologies, depending on the architecture and whether you're working with server-side MVC, REST APIs, or microservices.
Here are the main options:
✅ 1. CDI + Session Scope (Jakarta Contexts and Dependency Injection)
Use a CDI bean annotated with `@SessionScoped`to maintain shopping cart state per user session in a web application.
Example:
import jakarta.enterprise.context.SessionScoped;
import jakarta.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Named
@SessionScoped
public class ShoppingCart implements Serializable {

    private List<Item> items = new ArrayList<>();

    public void addItem(Item item) {
        items.add(item);
    }

    public List<Item> getItems() {
        return items;
    }
}



  • This is ideal for Jakarta Faces (JSF) or server-rendered MVC apps.
  • Backed by HTTP session, this works just like the old stateful bean but with more flexibility and less container overhead.

✅ 2. REST API + Client-Side State
Use Jakarta RESTful Web Services (JAX-RS) to build stateless endpoints and store the cart client-side (e.g., in local storage, or passed in requests).
  • Suitable for SPA or headless eCommerce apps.
  • Shopping cart is persisted on the client and submitted to server on checkout.
  • Stateless but scalable.

Example:
@Path("/cart")
@RequestScoped
public class CartResource {

    @POST
    @Path("/checkout")
    public Response checkout(CartDTO cart) {
        // process the cart from client payload
        return Response.ok().build();
    }
}

✅ 3. Session-Backed REST API (Hybrid)
You can combine REST APIs with HTTP session tracking:
  • Store the cart in the server session (like `HttpSession`)
  • Expose REST endpoints that implicitly access this server-side session

Example:
@Path("/cart")
@RequestScoped
public class CartResource {

    @Inject
    private HttpSession session;

    @POST
    @Path("/add")
    public Response addItem(Item item) {
        List<Item> cart = (List<Item>) session.getAttribute("cart");
        if (cart == null) {
            cart = new ArrayList<>();
            session.setAttribute("cart", cart);
        }
        cart.add(item);
        return Response.ok().build();
    }
}


✅ 4. Microservice + Distributed Cache (for Cloud-Native eCommerce)
  • Use a Kubernetes-native Jakarta EE microservice with Redis, Hazelcast, or JCache (JSR-107) to store the cart in a distributed cache.
  • Stateless services + distributed state = scalable architecture

Summary Table
Era Technology Used State Location Comment
Dotcom (J2EE) @Stateful EJB JVM memory (per session) Heavyweight, passivated if idle
Jakarta EE 10 @SessionScoped CDI Bean HTTP session Modern server-side MVC apps
Jakarta EE 10 REST API + client storage Browser (client-side) Scalable SPA/headless architecture
Jakarta EE 10 REST API + HttpSession Server session Hybrid model
Jakarta EE 10 Stateless + distributed cache Redis/Hazelcast/etc. Cloud-native scaling


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[1], 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 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.

[1]Stateless: The property of an object such that it contains no information that needs to be preserved across method calls.

SEMrush Software