Why is Spring Singleton not thread safe?
Spring doesn't guarantee thread-safety. It will be your responsibility . Spring will create a Singleton , but if its mutable then it might not be thread safe.
With the Singleton design pattern you can:
- Ensure that only one instance of a class is created
- Provide a global point of access to the object
- Allow multiple instances in the future without affecting a singleton class’s clients
This design pattern ensures that only one instance of a class is created.
So eventually thread safety depends on the code and the code only. And this is the reason why Spring beans are not thread safe
Any Bean without a STATE can be singleton .
Spring beans themselves can maintain their *own* state
it’s possible that before a thread creates the Singleton instance, another thread proceeds to the instantiation.
Spring framework doesn’t control how the singleton is used. (You have to manage it by code)
If you want to make a Bean thread safe create your bean classes stateless.
Stateless Beans :
Stateless session beans are session beans whose instances have no conversational state. This means that all bean instances are equivalent when they are not involved in servicing a client-invoked method. The term 'stateless' signifies that an instance has no state for a specific client."
See Oracle Web site on Stateless Beans
Making all bean’s fields final doesn’t make it stateless. If values you assigned to final fields of a bean can be changed during the runtime, such bean is still not thread-safe.
See this example here :
Link a good article
Spring bean thread safety guide | Dev in Web
In addition Those beans may be reused over and over again in many HTTP requests coming from different users.
Singleton spring beans has no relation with thread safety. spring container only manages life-cycle of objects and guaranteed that only one object in spring container. so If an Non thread safe object is injected then obviously it is not thread safe. To make it thread safe you have to handle it by coding.