Notice
I wrote this article and was originally published on Qiita on 19 September 2019.
First please read following code of Spring MVC controller
@Controller
@RequestMapping("/count")
public class CountController {
private long count = 0;
@GetMapping(value = "/increment", produces = "text/plain")
@ResponseBody
public String increment() {
count++;
return Long.toString(count);
}
}
The function of this controller is to memorize how many times this controller being accessed, and print out the access count. If 100,000 times this controller being called, one by one, the controller should correctly print 100,000.
But there is a serious bug in this controller. If 100 users access this controller simultaneously, and 100 times of group access being done. After that the count is not 100,000.
Java Servlet is under multi thread environment, in other word is the environment which many request can be processed simultaneously. Spring MVC is built on the top of Java Servlet. And on designing Java Servlet class should be aware the problem of multi thread.
Simple to say, the problem is class variable count is not thread safe. Change code of controller to following should solve this problem.
@Controller
@RequestMapping("/count")
public class CountController {
private AtomicLong count = new AtomicLong(0l);
@GetMapping(value = "/increment", produces = "text/plain")
@ResponseBody
public String increment() {
return Long.toString(count.addAndGet(1l));
}
}
Top comments (0)