When multiple access Spring Singleton instance at same time When multiple access Spring Singleton instance at same time spring spring

When multiple access Spring Singleton instance at same time


what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time?

A singleton bean can be accessed many times concurrently. That's why it always has to be thread-safe

Should it cause any conflict?

Only if you fail to make it thread-safe

Or the IoC container will hold the later call until the first one finish?

No, that would be awful


BTW, as I can remember, if it is not a singleton one, IoC container will pool few instances based on the number of requests. Could some one confirm it?

Spring has the following scopes (see Bean Scopes reference):

  • singleton (only one instance is managed per application)
  • prototype (a new instance for every injection)
  • session (one instance per HTTP session, only in Spring MVC)
  • request (one instance per HTTP request, only in Spring MVC)
  • global session (one instance per global HTTP session, only in portlet-based Spring MVC)

Also:

As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for SimpleThreadScope.

What you describe is an Object Pool. In Spring that would be implemented as a Prototype-scoped FactoryBean. And internally it would use a library like Apache Commons / Pool.


Singletons are just that - singletons. One instance is managed by the Spring context, and all requests go through that one instance concurrently. It's up to you to make that thread-safe.

If your bean isn't thread-safe, then consider using non-singleton-scoped beans. Spring lets you use request, session and prototype scopes.