15

I have the following Spring controller:

package hello;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/test")
    public String test() {
        long val = counter.incrementAndGet();
        return String.valueOf(val);
    }
}

Each time I access the REST API, it returns an incremented value. I am just learning Java and I am wondering why it does not always return 1 as a new instance of AtomicLong must have been created each time the request comes.

3
  • 2
    Why do you think that it's creating a new instance? Commented Oct 15, 2015 at 7:28
  • @chrylis: I am originally from .net background and just had a comparison with it. Commented Oct 15, 2015 at 7:34
  • In general we try to keep the Controller (and the Service) layers stateless. This is okay just for a learning purpose but note this kind of way is difficult to manage in a multi-tenant architecture (each node / controller has a state). that's why in resilient architecture, the state is delegated in a database or a shared file system (e.g. AWS S3). Commented Apr 3 at 5:44

2 Answers 2

17

No, the TestController bean is actually a singleton. @RestController annotation declares a Spring @Component whose scope is by default SINGLETON. This is documented in the @Scope annotation:

Defaults to an empty string ("") which implies SCOPE_SINGLETON.

This means that it will be the same instance of TestController that will handle every requests. Since counter is an instance variable, it will be same for every request.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it a good practice to keep it singleton or set the scope to so-called prototype?
@BabuJames For a Controller, I would say it is better to keep it a singleton. Controllers are not typically stateful so it makes sense to make them singleton.
4

A @RestController is not created for each request, it remains the same for every request. So your counter keeps its value and is incremented each time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.