DEV Community

Salad Lam
Salad Lam

Posted on

Notice multi thread problem when working with Java Servlet

Notice

I wrote this article and was originally published on Qiita on 19 September 2019.


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

}
Enter fullscreen mode Exit fullscreen mode

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

}
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay