开发者

Spring singleton beans in high load

开发者 https://www.devze.com 2023-01-26 00:50 出处:网络
Hey, I have a question regarding multithreading. First off, how many instances of DispatcherSer开发者_运维百科vlet / DispatcherPorlet is there ? Is it always the only one ? Even when there are let say

Hey, I have a question regarding multithreading. First off, how many instances of DispatcherSer开发者_运维百科vlet / 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 ?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号