When using an instance of Singletime Spring Singleton

If you define your service in the singleton area in the spring configuration, what happens if several users try to access it (i.e., as a dependency injected into your controller) at the same time? Should this cause any conflict? Or will the IoC container hold the later call until the first termination? If so, this should slow down performance in large applications, which doesn’t sound right for me. Can someone give me the correct answer?

BTW, as I recall, if it is not single, the IoC container will combine several instances based on the number of requests. Can anyone confirm this?

+6
spring ioc-container
source share
2 answers

What happens if several users try to access it (i.e., as a dependency entered into your controller) at the same time?

A single-screen bean can be accessed many times at once. That's why it should always be thread safe.

In case of conflict?

Only if you cannot make it thread safe

Or will the IoC container hold the later call until the first termination?

No, that would be terrible


BTW, as I recall, if it is not single, the IoC container will combine several instances based on the number of requests. Can anyone confirm this?

Spring has the following areas ( see bean Link to scope ):

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

also:

As with Spring 3.0, the stream area is available but not registered by default. See the documentation for SimpleThreadScope for more information.

What you are describing is a pool of objects. In Spring, to be implemented as FactoryBean . And internally it will use a library like Apache Commons / Pool .

+12
source share

Singleton are the only moments. One instance is managed by the Spring context, and all requests go through one instance at a time. It is up to you to make it thread safe.

If your bean is not thread safe, consider using beans that do not support a singleton scope. Spring allows you to use query, session, and prototype areas.

+4
source share

All Articles