SteelReed

Search

Search posts, questions…

Spring BootQuestion 6 / 26

Middle

What bean scopes does Spring have? Is a singleton bean thread-safe?

Short answer

The default scope is singleton: one instance per container. A singleton is not thread-safe by itself: many requests run concurrently on the same instance, so the bean must be stateless.

field holds request statestateless, local variablesRequest AOrderService singletonone instanceRequest BRace conditionSafe

3 points to say:

  1. Default is singleton: Spring guarantees one instance, not thread safety.
  2. Keep beans stateless; per-request data travels in parameters and local variables; anything shared is immutable or an AtomicLong/ConcurrentHashMap.
  3. A prototype inside a singleton is injected only once: use ObjectProvider; Spring never calls destroy on prototypes.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.