0

There is a Spring Boot application which exposes the following Rest endpoint

private static int requestsIn=0;
private static int requestsOut=0;

@RequestMapping(value = "/endpoint", method = RequestMethod.POST, consumes = "application/json")
public Long insertPojo(@RequestBody final Pojo pojo) {

    requestsIn++;

    final long startTime= System.currentTimeMillis();
    service.doSomething(pojo);
    final long endtime = System.currentTimeMillis();

    requestsOut++;

    LOG.info("requestsIn = {}, requestsOut={}",requestsIn,requestsOut);
    return (endtime - startTime);
}

Then I have a client that spawns 50 threads (via Spring ThreadPoolExecuter) and hits that endpoint.

I am expecting the final log that will be printed by the endpoint would eventually be requestsIn=RequestsOut=50, however I usually see requestsOut = 50 and requestsIn = 40-49.

Can anyone please explain on why this might happen?

I tried to make the counter variables volitile or even adding a delay(Thread.sleep) before logging the variables, however I am unable to get all variables to equal 50.

This has surfaced as part of an overarching troubleshoot attempt.

Rami Del Toro
  • 1,130
  • 9
  • 24
  • Please expose what is the "LOG" object and how you are logging in your application. It might be related to the thread that holds the logger object. – Gabriel F Sep 18 '17 at 22:59

1 Answers1

0

It appears that integers cant be incremented or decremented safely as that's a read/modify/write cycle as per Is a volatile int in Java thread-safe?

Changing the integers to AtomicIntegers solved the issue.

Rami Del Toro
  • 1,130
  • 9
  • 24