In a traditional n tier web app with servlets for web layer and ejbs(2.0) for biz layer, what is the rationale behind making the servlet model multi threaded and the ejb model single threaded?
i.e there is only 1 servlet instance for all requests, but for ejbs, for each request, there is a new bean instance assigned from the bean pool.
In a traditional n tier web app with servlets for web layer and ejbs(2.0)
Share
There is indeed only one instance for a specific
Servletsince they are supposed to be stateless. In practice this isn’t always the case, but so be it.There are however multiple instances of
Stateless session beans(SLSB), and those are pooled.By their very definition,
stateless session beansare stateless, so on the surface this seems like a paradox. The things is that whilestateless session beansare stateless with respect to individual calls being made to them, they in fact very often have state.This state is in the form of references to other resources. The
JPA entity manager, which is not thread-safe, is a prime example here. During a single call to astateless session bean, the caller must have exclusive access to this resource. When the call returns, the next caller can have exclusive access, etc.If a single instance was used, then either all callers would have to wait on each other (which is of course killing for performance), or they would have the access this single instance concurrently. In the latter case, the bean implementor has to do manual locking of the non thread-safe resources like the
entity managerwhich is often brittle, error-prone and in the end still causes callers to wait on each other.So, in order to improve performance and still have the safety guarantee, multiple instances are being used.
Those instances are then being pooled and re-used instead of created fresh for each request, because finding, initializing and injecting all required dependencies of the bean can potentially be time consuming.
All of this thus automatically also means that if you inject an entity manager or other non thread-safe resource into a Servlet (which is allowed), you may run into problems. This is a small loop-hole in the Java EE architecture, which is of course easily worked around by simply making use of stateless session beans.