1
votes

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.

1
This is actually a very good question. Short answer: It isn't! Beans should be kept as read only. If you use them as global variables (basic example of singleton anti pattern!), you will face race conditions. Even if you use prototype scope, you will face the same issue. Optionally, you could use other scopes like request. - Branislav Lazic
As @BranislavLazic already said as long as you don't have state in your bean there is no problem with the singleton scope. - Simon Martinelli

1 Answers

4
votes

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 ).