简体   繁体   中英

singleton beans concurrency in Java Spring

Java Spring beans default scope is singleton. 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?

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) . 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. These scopes will help serve the purpose to keep the state as per request/bean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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