2

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.

pise
  • 849
  • 6
  • 24
  • 51

2 Answers2

2

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:

enter image description here

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

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • int count will be shared between the threads. So you mean to say instance variable are shared between the threads in Controller, Service or Repository and also can you please share the image because it is not visible. – pise Apr 20 '15 at 07:49
  • When the scope come in picture, when to use it? Please see the url below of [tutorials point](http://www.tutorialspoint.com/spring/spring_bean_scopes.htm) – pise Apr 20 '15 at 07:52
0

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