0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Notice multi thread problem when working with Java Servlet

Posted at

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

}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?