简体   繁体   中英

Spring singleton beans in high load

Hey, I have a question regarding multithreading. First off, how many instances of DispatcherServlet / DispatcherPorlet is there ? Is it always the only one ? Even when there are let say 10 requests per second ? What about the services that are singleton by default. If I have a validationService bean that is injected into handler to provide request validation, as a singleton (by default), can I rely on the fact that it is a singleton and that it won't be reinstantiated in some cases ?

Depending on the load, servlet container creates number of servlet instances, developer does not have any control over that . But in most of the cases, the container maintains a single instance of each servlet (as servlets are supposed to be thread-safe anyway).

For as for Spring singleton beans, these are singletons per web application - the Spring application context is stored in servlet context (you can get access to it with WebApplicationContextUtils.getWebApplicationContext(ServletContext) ).

As for reliability: yes, you can rely on the fact that in the scope on one Spring application context, there is only one instance of each singleton bean .

This is an interesting question.

As mentioned in this previous question , the container is only permitted to instantiate one servlet instance. In this case, you're guaranteed to have one spring context, and one singleton.

The question is what happens for previous versions of the Servlet spec, which I'm not sure specify this behaviour explicitly.

In practice, though, containers only ever instantiate one servlet instance - I've never seen one do otherwise. So it's safe to assume that you'll only get one app context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM