栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

为什么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.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/601163.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号