Spring单例bean是线程安全的吗?

Spring单例bean是线程安全的吗?

问题描述:

我想知道Spring单例bean是否是线程安全的,如果是,那么为什么,如果不是为什么呢?

I want to know whether the Spring singleton beans are thread-safe, if yes then why, if not then why?

因为我是春天的初学者,所以请帮助。

As I am beginner with spring so help would be appreciated.

没有。这两个概念甚至没有关联。

No. The two concepts are not even related.

单身人士关于创造。此设计模式确保只创建一个类的实例。

Singletons are about creation. This design pattern ensures that only one instance of a class is created.

线程安全性与执行有关。引用维基百科

Thread safety is about execution. To quote Wikipedia:


如果一段代码只以同时保证多个线程安全执行的方式操作共享数据结构,则它是线程安全的。

A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

因此最终线程安全仅取决于代码和代码。这就是为什么Spring bean本身不是线程安全的原因。

So eventually thread safety depends on the code and the code only. And this is the reason why Spring beans are not thread safe per se.