Java Servlet should be aware of multithreaded environment

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

Java Servlet should be aware of multithreaded environment
5 things new programmers should be aware of
Things to be aware of when writing Java
[Java] Be aware of short circuits (short-circuit evaluation)
[Java] Things to be aware of when outputting FizzBuzz
[Java] Beginner's understanding of Servlet-②
[Java Silver] Things to be aware of regarding switch statements
Things to be aware of when writing code in Java
To be aware of easy-to-read code
[Processing x Java] Construction of development environment
[Beginner] Points to be aware of after Java exercises / Inheritance / Abstract method [Note 26]
Summarize the life cycle of Java objects to be aware of in Android development
Summary of Java environment settings for myself [mac]
[Java] Be careful of the key type of Map
[Java] Servlet filter
[Java] Environment construction
Java environment construction
Java development environment
[Java] Overview of Java
Basic rules to be aware of to write easy-to-read code
Stream processing of Java 8 can be omitted so far!
[Rails] When using ajax, be aware of "CSRF measures".
Things to be aware of when using devise's lockable
[Java] Get the file in the jar regardless of the environment
[Java] When var should be used and when it should not be used
Be aware of garbage collection and avoid memory leaks
[Java10] Be careful of using var and generics together
I want to be aware of the contents of variables!