Sobes.tech
Senior

All beans are singletons. Many requests arrive at the same REST method. How is thread safety ensured? Does Spring guarantee anything out of the box?

sobes.tech AI

Answer from AI

In Spring, all beans are singletons by default, meaning one instance per application context. REST controllers are also usually singletons, and they can receive many requests simultaneously.

Thread safety is ensured because Spring does not create a new object for each request but uses a single instance, therefore:

  • It is important that controller fields are either immutable (final) or do not contain state dependent on a specific request.
  • All request-specific data should be stored in local method variables, not in class fields.

Spring itself does not make objects thread-safe; it simply manages the lifecycle of beans. Thread safety is the developer’s responsibility.

If you need to store state at the request level, you can use the @RequestScope scope or pass data through method parameters.

Example of a thread-safe controller:

@RestController
public class MyController {
    @GetMapping("/data")
    public String getData() {
        // local variables are thread-safe
        String result = compute();
        return result;
    }
}

If the controller has mutable fields, they should be synchronized or replaced with thread-safe structures.

All beans are singletons. Many requests arrive at the… - sobes.tech