First read the Spring MVC controller below
@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);
}
}
This controller remembers the number of times it is accessed and outputs the number of times it is accessed. If you access the controller 100,000 times ** once **, 100,000 will be output correctly.
But the controller is terribly problematic. If ** 100 users access at the same time **, 1,000 times, the last output is not 100,000.
Java Servlet is a multi-threaded environment, in other words, an environment that can process a large number of requests at the same time. Spring MVC is built on top of Java Servlet. Java Servlet class design must be multithreaded conscious.
Simply put, the problem is that the class variable * count * is not thread-safe. The problem can be solved by rewriting the controller as shown below.
@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));
}
}
Recommended Posts