2

As per my understanding, stateless EJB thread safety comes from the fact that
concurrent requests to the same SLSB will be served by different intances of that particular bean, each one with it own instance variables.

For example if a stateless ejb has a instance variable, such as an int counter, each pooled EJB will be using a different counter variable.

Does the same apply also with injected variables as in the following example:

@Stateless
public class User implements UserHomeLocal, UserHomeRemote
{

    @PersistenceContext(name="J2EE")
    private EntityManager manager;
}

More generally: is there any case in wich pooled beans can share instance variables as a result of dependency injection?

GionJh
  • 2,742
  • 2
  • 29
  • 68

1 Answers1

1

EJB Spec says

The container serializes calls to each stateful and stateless session bean instance. Most 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

That means it is thread-safe, by default. No extra efforts needed. At the same time note that stateless beans are supposed to be "state-less".

It is not a good idea for a stateless bean to have mutable state. That is just the recipe for disaster. If you need a variable to be shared amongst all instances, it needs to be a static variable. EJB specification restricts use of static mutable variables (class level variable like a counter to track all requests to all instances). Basically "read or write nonfinal static fields" is restricted.

So to make pooled beans to share an instance variable, that variable should be static, and final. If you are looking this up for any implementation reasons, you may check out Singleton beans. Once you create a singleton bean, you can inject that in to your session bean. But I am not sure if it is worth the pain.

And yes,the entity manager or any such Java EE objects (e.g. references to Java Persistence entity managers or stateful session beans) will be shared and guaranteed to be thread-safe by default (under stateless)

ring bearer
  • 20,383
  • 7
  • 59
  • 72
  • I don't want at all to share instance variables among beans, I'm asking in this case whether each bean will have a different EntityManager instance or not. – GionJh Jun 29 '15 at 17:11
  • negative voter, please care to comment -why? I will try to improve my answer. – ring bearer Jun 29 '15 at 19:08
  • not me, I think you deserve a +1, maybe even the best answer. Just one more point if you can clarify, where can I read all these specific details such as "he entity manager or any such Java EE objects (e.g. references to Java Persistence entity managers or stateful session beans) will be shared and guaranteed to be thread-safe by default (under stateless)". Thanks! – GionJh Jun 29 '15 at 19:16