Search code examples
javaspringjakarta-eeejb

ejb thread safety: do we need it?


Consider a stateless EJB

from ejb 3.1 spec
containers will support many instances of a session
bean executing concurrently; however, each instance sees only a
serialized sequence of method calls. Therefore, a stateful or
stateless session bean does not have to be coded as reentrant

So a Stateless seession bean can "serve" at most one request at a time, this is usually implemented by the container managing a pool of beans. The great goal of all this is Thread safety.

My question is why do we need this form of thread safety ? I mean Spring beans are singleton and not thread safe (they can serve any number of request at a time) and we have no problem with that.


Solution

  • You need that form of thread safety if the stateless session bean has member variables that are themselves not thread safe (e.g., a SAXParser). However, since stateless session beans don't have client affinity like stateful session beans, the use cases are admittedly relatively rare, and the servlet programming model seems to have shown that this level of protection is probably not necessary, so if you don't need the thread safety then as of EJB 3.1, you can use a singleton session bean with bean-managed concurrency.

    The thread safety restriction also gives some additional freedom to the EJB container for optimization. For example, if the EJB container knows that only one thread at a time can be using a stateless session bean, then it can manipulate the state of injected objects at method entry/exit so that those objects don't need use ThreadLocal (e.g., UserTransaction or SessionContext).