简体   繁体   中英

Spring Controller singleton Object

I am little bit confused with regards to controller objects. As I know controller are singleton by default. How does singleton works for web application, like in below code if thread 1 execute till line 9 and got empId as 12 and thread 2 takes the control from thread 1 and got empId as 23 and complete execution of whole method and then when again thread 1 execute what will be the value of empId will it be 12 or 23.

And also I have noticed that only one object is created for UserServiceDao class so how threads are managed in spring mvc with each thread having its own instance.

1 public class ActionController {
2
3   @Autowired
4   UserServiceDao userServiceDao;
5   
    int count = 1;
6   
7   @RequestMapping("/dashboard.htm")
8       public ModelAndView dashboard(HttpServletRequest request) {
9           String empId = request.getParameter("empId");
10          UserProfile userProfile = userServiceDao.loadEmpById(empId);
            System.out.println(count);
            count++;

11      }
12  }

    Thread first output: 1;
    Thread second output : 2; 

Thanks.

In the controller you don't have any instance variable to keep the state of any controller method's call. All variables are method (local) variable that never shared between thread hence there is no issue to use it in multi-threaded way.

It's same as using servlet.

Method (local) variables resides on stack and there scope is limited to the end of the method only. Here empId is local variable that is not shared between multiple threads.

In the same way, UserServiceDao should not contain any instance variable to keep the state of its method call.

Look at below image:

在此处输入图片说明

read more Thread safety of instance methods that have local variables only

The controller and all its dependencies are generally stateless, so concurrent access isn't a worry. In particular keep your DAOs stateless.

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