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.
as they are guaranteed to be thread-safe (thanks to pooling)
No, they're not. E.g. see EJB 3.1 spec, 4.3.10.2 Stateless Session Beans:Since stateless session bean instances are typically pooled...
Just "typically pooled". Wildfly 8-9 doesn't pool SLSB by default, Wildfly 10 does. – Goffer