user1692342
user1692342

Reputation: 5237

Understanding Controller singleton behavior spring MVC

I'm using spring MVC Controllers and understand that it is a Singleton. I just want to ensure that my understanding of Race conditions is correct.

@Controller
public class MyController {
    private List<String> errors;

    @RequestMapping("/page1") 
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        ModelAndView mav; //initialize
        errors = new ArrayList<>();
        try {
            //do something
        } catch (Exception e) {
            errors.add("123"); // point A1
        }
        mav.addObject("error", errors"); // point A2
    }

    @RequestMapping("/page2") 
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        ModelAndView mav; //initialize
        errors = new ArrayList<>(); //point B1
        try {
            //do something
        } catch (Exception e) {
            errors.add("568"); //point B2
        }
        mav.addObject("error", errors");
    }
}

If I do something like this, does that mean for the requests which go to the same host, at times even though there is an error, it will show that there are no errors. My understanding is this: if 2 requests are made simultaneously, one for page1 and the other for page2, it might happen that page1 handling threw an exception and it add values to the errors list [point A1] but before point A2 ran, point B1 could have run and emptied the list. Hence we should always use local variables.

Upvotes: 1

Views: 40

Answers (1)

Ken Chan
Ken Chan

Reputation: 90427

Yes. Because Singleton means there is only one MyController instance which means there is only one List<String> errors.

If multiple threads (as each HTTP request run on a thread) manipulate the data on the same list , they will probably mess up with each other.

That 's why you should move the error list to the private variable inside each controller methods.

Upvotes: 1

Related Questions