A quote from the EJB 3.1 spec
4.7 Stateless Session Beans
Stateless session beans are session beans whose instances have no conversational state. This means that
all bean instances are equivalent when they are not involved in servicing a client-invoked method.
The term “stateless” signifies that an instance has no state for a specific client. However, the instance
variables of the instance can contain the state across client-invoked method calls.
Examples of such
state include an open database connection and an object reference to an enterprise bean object.
The emphasis is on no conversational state. They can have "other" state.
For example, I have used it to check if the load was spread equally over all instances in a cluster node:
@Stateless(name = "DemoPingSb")
@Remote(DemoPingSbIfc.class)
public class DemoPingSb implements Serializable, DemoPingSbIfc {
private final AtomicInteger instancePingCount = new AtomicInteger(0);
private final static AtomicInteger classPingCount = new AtomicInteger(0);
public DemoPingSb() {
super();
}
public String ping(final String s) {
final int local = this.instancePingCount.incrementAndGet();
final int global = classPingCount.incrementAndGet();
System.out.println("INFO: local " + local + ", global " + global
+ ", s " + s);
return s.toUpperCase();
}
}
and if there is enough load:
13:13:21,769 INFO [stdout] (http-localhost-127.0.0.1-8080-1) INFO: local 22, global 22, s hello
13:13:21,936 INFO [stdout] (http-localhost-127.0.0.1-8080-1) INFO: local 1, global 23, s hello
So there are some special cases where this feature might be useful.
Remarks
- The spec talks about instance variables; the usage of a static variables is not covered there. So the code might not be correct regarding
classPingCount
- The usage of an
AtomicInteger
for instancePingCount
could by replaced with volatile int
, because (4.10.13)
The container must ensure that only one thread can be executing a stateless or stateful session bean
instance at any time.
- A stateless session bean is never passivated (4.2)