For Spring what if I have two requests that access the singleton bean at the same time? Does one request have to wait until the other to finish. How does Spring container find the singleton bean instance for my requests?
For servlets if I have two requests that access a normal class's normal method(no static no other complex things) at the same time? Does one request have to wait until the other to finish to avoid concurrency (at the same time two request are trying to access the object of the same class). How does web container find the instance for my requests?
For Spring, what if I have two requests that access the singleton bean
at the same time? Does one request have to wait until the other to
finish?
Spring container creates one and only one instance for the singleton bean class (like for Controller, Service class, etc..). In Java, there are several ways that you can create singleton instance for a class safely, you can look here for more on this. Once the singleton instance is created by the Spring container then the web requests will be served using that single instance of the controller/service classes.
Also, there is no problem (i.e., there will not be any waits in between) even if two requests access the singleton bean as they will be served in two separate threads and all you need to ensure is that your controller and service classes (i.e., singleton scoped beans) do not carry/hold any state (i.e., they are stateless) and are thread-safe.
How does Spring container find the singleton bean instance for my
requests?
Spring container creates and then injects the singleton bean instances based upon the configurations that you have provided using the xml or through annotations.
For servlets, if I have two requests that access a normal class's
normal method(no static no other complex things) at the same time?
Does one request have to wait until the other to finish to avoid
concurrency (at the same time two request are trying to access the
object of the same class) ?
No, each request will be handled in a separate thread so one request will not wait for the other request to be served/completed i.e., in other words, the requests will be served/processed parallelly. This is achieved by the Web containers by using/managing the Thread pools.
How does web container find the instance for my requests?
Web container (like Tomcat, etc..) creates and loads all of the servlet classes (like Spring's DispatcherServlet or your own custom servlets) and then once the web request comes from the client (like Browser), it will be handled to the servlet according the url-pattern configured in the web.xml or through annotations.
Related
When ever a spring boot application started, On startup an object is created and we just map the object using #Autowired.
How does only one object serve multiple request? (default configuration is singleton).
If you use the default bean scope which is singleton you need to make them thread safe yourself, in most cases this mean you should keep keep them stateless.
If you need beans that are scoped to a specifik web request you can use the bean scope request for this.
You can read more about this in the documentation.
How does only one object serve multiple request
Normally you have that single object representing a service, a controller, a repository etc...
So you just have a reference for a single instance, and that is enough because in singletons you don't have any state on class level, per request. The http request would normally invoke just some method of that singleton and that is fine, since the method works in it's own scope, per thread execution.
So each request normally uses a different thread to execute and each thread when executing a method of the singleton, uses it's own method parameters in it's own stack frame memory.
This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 6 years ago.
What I know
A web container creates a new thread per request.
What I don't know
Are new servlet objects created per request?
Why I am asking this is to get an idea on how thread synchronization issues can happen if the same servlet object is used for multiple requests.If the web container creates a new servlet object for each new reqest, then I don't see an issue. But if it uses the same servlet object to serve multiple requests, synchronization issues can happen.
How is this handled in a typical java web container?
A web container creates a new thread per request.
No. It reuses a thread from a thread pool.
Are new servlet objects created per request?
No. A servlet is a singleton. Only one instance is created per web app. Your servlet must be thread-safe, since it's called concurrently by several threads. But that' usually easy, because a servlet is typically stateless.
Are new servlet objects created per request ?
By default, Servlet container creates a single servlet instance and will be used to serve all of the requests in a separate thread. So ensure that your servlet class is thread safe (i.e., your servlet class should not hold any stateful data as instance variables, etc..).
Adding to that, Servlet containers create the servlet instance either during the container start-up or upon the first request received.
You can force the container to create the servlet instance by specifying the load-on-startup in web.xml or #WebServlet(urlPatterns="/xyz", loadOnStartup=1)).
It is generally better to load the servlets (unless you have any special requirements) using load-on-startup so that the first request will not hit with the performance.
In general sense servlets are Singletons, however if you map the same servlet class to different URL mappings using different names, you will have that many instances of same servlet.
Mostly servlets are stateless, if you do make them statefull, then be very careful about shared mutability .
Earlier servlet API used to have SingleThreadModel Interface to impose single thread access at one point of time, that way you could serve only one request at a time, However I see this interface is deprecated in recent APIs as it doesn't solve the concurrency issues fully, like static variables etc.
I have been studying ejb recently and I am also reading about the timer service as well, but even though I have read about Stateless, Stateful and Singleton types of Session Beans, I still have some trouble to figure out what makes the Timer Service have a multiple instance attribute.
I have seen some examples around, and even the simplest ones use the Singleton Session Bean, so, If I were to write a simple program to test it, would it be ok to use a Stateless Bean or is it recommended to use a Singleton anyway? Also, if possible, can I have a case where a Stateless would not be optimal?
Use a singleton if you want to ensure that all timeout callbacks are invoked on the same underlying bean instance. This is important if you want to maintain state in the bean instance itself, and you want to ensure that only one timeout callback can be invoked at a time (by default, the timeout callback will use the singleton's concurrency management settings, which by default is container-managed with a write lock, so only one method on the singleton can be invoked at a time).
Use a stateless if you want to allow multiple timeout callbacks to be invoked at once. The EJB container will create new bean instances if there are multiple timeout callbacks happening concurrently.
If you want to configure a non-persistent timer to begin running when the application begins running, then you can either use the #Schedule annotation on either a stateless or singleton bean, or you can use an #Singleton #Startup bean with an #PostConstruct (and if you want the stateless behavior, you can inject the stateless bean into the stateless bean and invoke a createTimer on the stateless session bean during startup).
The reasons it uses singletons are at least 2 fold:
1.
only singletons have the capabilities of start up initialization. That means, you are able to register your timer services when your application starts.
2.
if it were to use stateless beans, then a new timer service will be registered with every stateless bean setup to serve a request. A singleton guarantees that only one of a kind of your timer is registered. Imagine a contention or integrity issues, or money losses, were you to inadvertently use a timer in a stateless bean and then more than 1 is created at more or less the same time to serve requests.
I have this new mvc project where all beans are default scoped(no prototype or session).
with single application context.
i want to know
by making all beans to be default scoped are we trying to achieve the whole application to be run in single thread?
if so will that make each httprequest(from multiple or same sessions) to be queued until the previous one completes?How to avoid such scenario any advice or link would be helpful.
I am relatively new to spring and java development.
Because Spring beans are typically stateless, you can safely call them from multiple threads. That's how your application works: there is only one instance of every controller, service, DAO, etc. But your servlet container (through Spring) calls these beans from multiple threads - and it's completely thread safe.
In fact in plain servlets the situation is the same - there is only instance of each servlet and it can be accessed by infinite number of threads. As long as this servlet is stateless or properly synchronized.
Do not confuse Spring with stateless session beans in ejb that are pooled and each client gets its own instance from the pool.1
1 - In fact that's a bit dumb - since the beans are stateless by the definition, there is no point in pooling them and preventing concurrent access...
Singleton means that the there will be only one instance of each bean. Generally, such beans are processing elements that carry no state. The methods called on them are passed the context which contains the inputs to work on. Hence the method calls on such singleton beans are inherently thread-safe.
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.
There is indeed only one instance for a specific Servlet since 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 beans are stateless, so on the surface this seems like a paradox. The things is that while stateless session beans are 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 a stateless 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 manager which 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.
I think that typically servlets present thin facade to the heavy logic implemented in EJBs. Servlets should be stateless and therefore there is no reason to create more than one instance of the same servlet.
If you are using stateless beans only I think that there is no reason to have more than one instance too. But statefull EJBs have state and therefore you need instance per simultaneous request.
I hope I did not say bullshit.