I was reading about stateless session bean and couldn\'t understand it\'s use.
Excerpt from sun tutorial below
\"..Because stateless session beans can suppor
In contrary to what most answers here let you believe, statelessness has nothing to do with threadsafety of the class itself. That's absolutely not the primary goal of @Stateless
. The developer itself is still responsible for that the class representing a @Stateless
EJB doesn't have any instance variables declared (i.e. no state). The container isn't responsible for that part. Basically, the developer must say "Hey container, here's a stateless business service class, I'll annotate it with @Stateless
so that you can use it as a stateless EJB" and thus not the other way round or so.
If you want state, then use a @Stateful
which will be newly recreated every time the client obtains it (so, if the client is e.g. a view scoped JSF managed bean, then the EJB will live as long as that bean, or if the client is e.g. a session scoped CDI managed bean, then the EJB will live as long as that bean, etc). Or, use a @Singleton
which is basically application scoped and actually thread locked.
Statelessness and pooling has more to do with threadsafety of transactions. You probably already know that a single method call on a @Stateless
counts by default as a single full transaction. However, that transaction in turn requires a thread lock on the specific EJB instance, because of all the sensitive pre- and post processing work. So the EJB could basically block all other clients wanting to call the same method until the transaction is committed. That is exactly why they are cloned and pooled on demand.
Do note that a @Singleton
is not pooled and is by default actually thread locked. You should by now understand that a @Singleton
is by default absolutely not faster than a @Stateless
when (ab)used as a "stateless EJB". See also a.o. Java EE 7 tutorial "Managing concurrent access in a singleton session bean".