Why Stateless session beans?

Surez picture Surez · Apr 27, 2011 · Viewed 7k times · Source

I was reading about stateless session bean and couldn't understand it's use.

Excerpt from sun tutorial below

"..Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients"

Where stateless session bean is being used? what kind of applications use it?

What mechanism has been being used before the advent of 'stateless session bean' to support multiple clients in the similar contexts?

Can anyone please provide some details?

thank you!

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Apr 27, 2011

To be honest, it is hard to find any reasonable use case for SLSBs. Since they don't hold any state (as the name imposes), they should be inherently thread-safe. Even though they are pooled by the container.

On the other hand it is tempting to use them as a safe temporary storage as they are guaranteed to be thread-safe (thanks to pooling), you don't need any synchronization or thread-safe collections. But consider the following pseude-code:

@Stateless
public class Slsb {
  private int counter;

  public void increment() {
    ++counter;
  }

  public int getCounter() {
    return counter;
  }
}

Client-side:

@Resource
private Slsb slsb;

public void clientMethod() {
  slsb.increment();
  slsb.increment();
  slsb.getCounter();  //???
}

This code (despite its vulgarity) is perfectly fine and it does not require AtomicInteger for instance.

What result do you expect? Actually, any non-negative value is possible... Any call to slsb might be served by different instance of Slsb and in the meantime your (previously used) instance might have been used to serve different clients. Conclusion: storing state in SLSB is wrong, but for some reason SLSBs are pooled to avoid threading issues when changing the state (?!?). Personally I much prefer singleton services (Spring-like) and I have never got the SLSB idea. And yes, I am aware of singleton EJBs in EJB 3.1.