Beachten Sie das Multithread-Problem, wenn Sie mit Java Servlet arbeiten

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

Beachten Sie das Multithread-Problem, wenn Sie mit Java Servlet arbeiten
Fehler beim Spielen mit Java
Was ist Thread-sicher (mit Java)
Beim Aufrufen der API mit Java tritt eine javax.net.ssl.SSLHandshakeException auf
[Java] Vorsichtsmaßnahmen beim Vergleichen von Zeichenfolgen mit Zeichenfolgen
Behandeln Sie große JSON mit Java Lambda
Geben Sie ClassPath an, wenn Sie jupyter + Java mit WSL verwenden
Üben Sie die Arbeit mit Unicode-Ersatzpaaren in Java
Einfacher LINE BOT mit Java Servlet
Eine Geschichte, bei der Sie bei der parallelen Ausführung mit Java auf Thread-Sicherheit achten müssen