Must Spring MVC Classes be Thread-Safe
来源:互联网 发布:网络剧怎么赚钱 编辑:程序博客网 时间:2024/05/09 19:32
Given
@Controllerpublic class MyController { @RequestMapping(value = "/index") public String respond() { return "index"; }}
Spring will create an instance of MyController
. This is because Spring parses your configuration, <mvc:annotation-driven>
, sees @Controller
(which is like @Component
) and instantiates the annotated class. Because it sees @RequestMapping
as well, it generates a HandlerMapping
for it, see the docs here.
Any HTTP requests the DispatcherServlet
receives will be dispatched to this controller instance through the HandlerMapping
registered before, calling respond()
through java reflection on that instance.
If you have instance fields like
@Controllerpublic class MyController { private int count = 0; @RequestMapping(value = "/index") public String respond() { count++; return "index"; }}
count
would be a hazard, because it might be modified by many threads and changes to it might be lost.
You need to understand how Servlet containers work. The container instantiates one instance of your Spring MVC DispatcherServlet
. The container also manages a pool of Threads which it uses to respond to connections, ie. HTTP requests. When such a request arrives, the container picks a Thread from the pool and, within that Thread, executes the service()
method on the DispatcherServlet
which dispatches to the correct @Controller
instance that Spring registered for you (from your configuration).
So YES, Spring MVC classes must be thread safe. You can do this by playing with different scopes for your class instance fields or just having local variables instead.
- Must Spring MVC Classes be Thread-Safe
- Spring MVC: how to build a thread-safe Controller
- Spring thread safe
- [Compile Error] Classes must not be nested
- “Internal Build Error” or “Classes Must Not Be Nested” error
- Thread-safe, Signal-safe
- thread safe
- spring websocket Converters must not be empty
- spring mvc web.xml 配置出现 Attribute "xmlns:xsi" must be declared for element type "web-app"
- Component creation must be done on Event Dispatch Thread
- 出错:PhoneFactory.getDefaultPhone must be called from Looper thread
- PHP Thread Safe and Non Thread Safe
- TypeError:exceptions must be old-style classes or derived from BaseException, not str
- ride报错TypeError: exceptions must be old-style classes or derived from BaseException, not unicode
- Thread Safe In Servlet
- Python: Thread safe Oject
- Older Thread-Safe Collections
- Thread-Safe Interface
- python 正则表达式
- Windows内核中的内存管理
- Why are arrays of references illegal?
- 普通平衡树 treap
- echarts饼图文字重叠问题
- Must Spring MVC Classes be Thread-Safe
- 坚持#第107天~坚持!
- 在CentOS上升级Python的坑
- 微信开发整合日记(2)
- Linux系统Mysql5.6安装
- POJ 1006 Biorhythms
- 机器学习笔记(一)-局部加权回归(Locally weighted regression)LWR
- 记信息论与编码之课设-哈夫曼编码
- 几种常见的继承