4

Is the atomic integer in the following piece of code shared between different REST calls? What if it was static?

public class GreetingController {

    private static final String template = "Hello Docker, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", 
        defaultValue="World") String name) {

        return new Greeting(counter.incrementAndGet(),
          String.format(template, name));
    }
}
Arian
  • 7,397
  • 21
  • 89
  • 177

1 Answers1

5

It is shared if the controller is a singleton.

Since this looks like Spring MVC (you didn't say), and since a @Controller class by default is a singleton, then the answer is:

Yes, the atomic integer is shared between different REST calls.

It doesn't have to be static.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • so if it is shared between different calls and different clients, does this mean we need to be worried about race condition inside a controller classes? I don't remember seeing any controller class use multithreading mechanisms. – Arian Mar 29 '20 at 04:34
  • 1
    You don't normally see controller classes use multi-threading mechanisms, because controller classes are almost always *stateless*. You're adding state here, but you did it right by using `AtomicLong`, which is thread-safe, so there is no multi-threading issue in your code. – Andreas Mar 29 '20 at 10:24