Must Spring MVC Classes be Thread-Safe

来源:互联网 发布:网络剧怎么赚钱 编辑:程序博客网 时间:2024/05/09 19:32

来源:http://stackoverflow.com/questions/16795303/must-spring-mvc-classes-be-thread-safe


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 DispatcherServletwhich 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.



0 0