为什么spring 单例singleton 线程不安全?

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

What is a Session Bean?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值