简体   繁体   English

Java Spring 中的单例 bean 并发

[英]singleton beans concurrency in Java Spring

Java Spring beans default scope is singleton. Java Spring bean 默认范围是单例。 If we create a service (bean) with a class variable which may change in internal methods, This bean's usage of different threads may caused unexpected errors.So how to avoid this?如果我们创建一个带有类变量的服务(bean),它的内部方法可能会发生变化,这个bean使用不同线程可能会导致意外错误。那么如何避免这种情况呢?

A Singleton pattern ensures there is only one instance of this class available to the JVM (In case of Java you can have multiple instances per classloader/ in case of spring it per application context) .单例模式确保该类只有一个实例可供 JVM 使用(在 Java 的情况下,每个类加载器可以有多个实例/在 Spring 的情况下,每个应用程序上下文) This means that essentially need a global state into an application.这意味着本质上需要一个全局状态进入一个应用程序。

This is why we want the Singleton classes to be stateless, because if we any thread access it then we don't want internal variables to be mutated because of the lack of concurrency control.这就是为什么我们希望单例类是无状态的,因为如果我们有任何线程访问它,那么我们不希望由于缺乏并发控制而改变内部变量。

In case you want to keep state you can later the scope of spring beans as per your requirement eg request, prototype.如果您想保持状态,您可以稍后根据您的要求(例如请求、原型)设置 spring bean 的范围。 These scopes will help serve the purpose to keep the state as per request/bean.这些范围将有助于达到根据请求/bean 保持状态的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM