tags:

views:

75

answers:

2

Spring default setting is Singleton for beans. So does that mean when 100 users access the same the site (service or bean), do those 100 sessions share the single instance of that service bean in thread manner or will 100 beans be created and each session has its own bean. If it is a latter, then how does Singleton pattern apply to it? Can somebody please reply with a possible code example with which we can see for ourselves.

A: 

It's the former. You get one object only with singleton. You can get one object per session, but that is a different keyword I believe.

laura
yes, that's scope=session (only available in spring-mvc)
seanizer
+4  A: 

Singleton means that a single instance will be created of a given class for the lifetime of the application/process. So if 100 users access the same bean, all of them will get the same instance.

Darin Dimitrov
So does that mean all those 100 sessions/users share once instance in threaded fashion? So that means if the user numbers go higher (say 1,000), there could be starvation to get hold of that instance, correct?
Gurkhali
I don't know what starvation you are talking about. You could start running out of resources if you create many threads but accessing a singleton is not related to the number of threads.
Darin Dimitrov
What I mean is say for example, there is one controller named HelloController. As per Singleton pattern, there should be only one instance of HelloController per application context. So if there are 100 httprequests hitting this controller at the same time, how does it work? Do those other 999 requests have to wait while the first request is being handled by this controller. How does it work?
Gurkhali
@Gurkhali, what you are describing is synchronization (http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html) and only occurs if you are doing some sort of locking within your class. Controllers and other "shared" resources should be written in a stateless way so that they can be used by many threads with no issues or need for locking.
matt b
in other words, there is no inherent synchronization, all 100 requests/threads will be utilizing the Controller at the same time (so make sure your code is thread-safe!) unless you explicitly synchronize access.
matt b