Reputation: 117
So my question is regarding singleton scope in spring boot. I have worked on few spring boot projects but I have never seen class annotated with Prototype scope so I am assuming all the beans which are defined are singleton by default in spring boot. Now suppose 2 threads are accessing the bean which is singleton then in that case how can we make sure that changes made by one thread do not affect the other thread working on the same bean.
Now you may say that we can do the synchronization but I have not seen in web applications where synchronization is used to avoid this condition. So how exactly this is handled by spring boot.
Upvotes: 1
Views: 1992
Reputation: 11225
The default scope for any bean is indeed Singleton. Next, All your beans should be designed to be stateless. If a bean is stateless you do not have to worry about multiple threads accessing the same Bean / Synchronization. As their data will not be modified by each other.
What does stateless mean? A simple way of explaining it, you should not have class level fields that are modified by different threads. Your state should be stored in either a session, repository or by your client.
Lastly, just to clarify some small thing, this is not so much a Spring Boot question as it is a Spring Framework / Spring MVC question. The Bean scope is part of the Core Framework ( and more scope options are provided by Spring MVC ).
Upvotes: 4