Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How does Spring framework handle Singleton in its implementation?

 
Silvio Esser
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using the Singleton/Double Checking Locked pattern?
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually very simply. Spring is creating your instance, and no one can access the beans until the full ApplicationContext or BeanFactory is completely created. So you won't ever have more than one thread trying to "get" the instance at the same time that it is being created.

Mark
 
Silvio Esser
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What if I have two requests that access the singleton bean at the same time? Does one request have to wait
until the other to finish. How does Spring container find the singleton bean instance for my requests? Using static method or
variable?
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Silvio Esser wrote:What if I have two requests that access the singleton bean at the same time? Does one request have to wait
until the other to finish. How does Spring container find the singleton bean instance for my requests? Using static method or
variable?


Multiple threads can run at the same time calling methods of that class. The key here is the bean classes that you define in Spring xml will be your Services, Repository/DAO which should never hold state. For instance, a domain object would not be defined in your xml as a Spring bean. So there are no threading issues or need for synchronization.

Now if you have a bad design and actually hold state in those classes, then you will have issues, but you would have those issues with or without Spring. If you do hold state, then you might want a different scope than Singleton.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic