Notice multi thread problem when working with Java Servlet

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));
	}

}

Recommended Posts

Notice multi thread problem when working with Java Servlet
Error when playing with java
What is thread safe (with Java)
When calling API with java, javax.net.ssl.SSLHandshakeException occurs
[Java] Precautions when comparing character strings with character strings
Working with huge JSON in Java Lambda
Specify ClassPath when using jupyter + Java with WSL
Practice working with Unicode surrogate pairs in Java
Easy to make LINE BOT with Java Servlet
When executing in parallel with Java, I'm addicted to not paying attention to thread safety