Why Stateful and Stateless beans behave in opposite way?

Everything is behaving as specified.

A stateless EJB delegates the call further to currently available instance in the pool. Apparently there’s only one which is not used concurrently (yet) and therefore all clients have the same chance to access the same instance in the pool. If you fire more HTTP requests concurrently on the servlet(s), then chances increase that there’s no available instance anymore and the container will create a new instance in the pool.

A stateful EJB is tied to its client (in your case, the web servlet instance). In other words, each servlet has its own stateful EJB instance which is not shared elsewhere.

A singleton bean is application wide and shared across all clients. In other words, each servlet will share the same singleton EJB instance.

Do note that the terms “client” and “session” in EJB context are absolutely not the same as those in WAR context and this is where many starters fall over. The EJB client is not the webbrowser, but the instance of the class where the EJB is injected (in your case, the web servlet instance). The EJB session is not the HTTP session, but the EJB-client session.

See also:

Leave a Comment