If you define your service in singleton scope in your spring config, what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time? Should it cause any conflict? Or the IoC container will hold the later call until the first one finish? If so it should slow down the performance in large applications, which sounds not right to me. Could any one give me a correct answer?
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?
When the thread request the singleton bean, it is going to refer (with help of reference variable in stack) to the bytecode of singleton bean in heap. So multiple threads can refer singleton bean at the same time.
In Spring, every request is executed in a separate thread. For example, when two users want to log in at the same time, the JVM creates two threads: one thread for the first user and another one for the second user. And these threads work with the singleton bean separately.
Because the singleton isn't thread-safe, calls to its prototype methods may also run concurrently. When several threads share the singleton, the single instance of the prototype that Spring injects to that singleton will also be shared.
Summary. Spring Singleton is very different from Singleton pattern. Spring guarantees to create only one bean instance for given bean id definition per container. Singleton pattern ensures that one and only one instance is created per ClassLoader.
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):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With