As we know by default, spring bean is a singleton. Please help me understand what it means to be a singleton when multiple users are access an application concurrently ? Will each user have a separate instance of a bean or will all the users share the same bean ?
Can we call it a singleton if each user can have a separate instance created for a bean? Please clarify this.
in the spring context singleton doesn't mean that you can create only one instance, but it means that there is only one instance (nothing stops you to create more).
It works like this, on start up, context is read, all the beans are created and are available in the application. So you have only one instance of each bean when your application is running, so they are accessed by multiple threads.
There is only one instance created for the entire application. Not per user. Many threads can run the same single instance at the same time, unless you make a bean from a class that is holding state and each user has their own set of state they are expecting. Then just like in non-Spring apps, you have to deal with threading issues. If your beans don't hold state, like your Services, Repository/DAOs, then a single instance is plenty to support as many User threads as you like.
Thanks Mark and Pete. So as per my understanding, if we talk about singleton scope in a web application bean, each user who access the web app will have their own thread which runs the same single instance of a singleton at same time. Spring container will handle the synchronization issues i. e. as long as the thread is accessing the instance it is locked and the remaining threads will keep waiting for the lock to be released. If this is the case, surely it should be a performance issue.
Yed Su wrote:Thanks Mark and Pete. So as per my understanding, if we talk about singleton scope in a web application bean, each user who access the web app will have their own thread which runs the same single instance of a singleton at same time. Spring container will handle the synchronization issues i. e. as long as the thread is accessing the instance it is locked and the remaining threads will keep waiting for the lock to be released. If this is the case, surely it should be a performance issue.
No.
There is no synchronization being done. There doesn't need to be any, because these beans shouldn't be holding state. So a Controller, Service, Repository/DAO that many user threads are running don't hold state and are therefore threadsafe and don't need to have synchronization blocks.
Mark
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.