Spring bean如何处理并发 [英] How does Spring bean Handle concurrency

查看:370
本文介绍了Spring bean如何处理并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web应用程序使用Spring IOC.因此,默认情况下,我所有的春季豆都将是单例.如果两个请求尝试同时访问一个类的两个不同方法(例如,MySpringBean是具有两个方法searchRecordinsertRecord的类),则两个请求将访问相同的spring bean同时进行.

My web application uses Spring IOC. So all my spring beans will be singletons by default. In case if two requests try to access two different methods of a single class (for example MySpringBean is a class which has two methods searchRecord and insertRecord) at the same time, both the requests will access the same spring bean concurrently.

同一个Spring bean如何同时供两个客户端使用,或者当两个请求都尝试通过同一个Spring bean访问两种不同的方法时,这将成为并发问题.而且由于spring bean是单例,因此无法形成新实例.在这种情况下,如何运作?

How does the same spring bean be available to both the clients at the same time or is it going to be concurrency problem when both the requests will try to access two different methods but through the same spring bean. And since spring bean is a singleton so new instance can not be formed. In this case how is this going to work?

推荐答案

您必须首先了解并发何时会引起问题.如果您的Spring bean是无状态的(它没有任何字段,所有字段都是final,或者所有这些字段仅分配了一次),则多个线程可以安全地使用相同的bean,甚至使用相同的方法.

You must first understand when concurrency can cause problems. If your Spring bean is stateless (it doesn't have any fields, all fields are final or all of them are assigned only once), multiple threads can safely use the same bean, or even the same method.

  • thread safe, stateless design using Spring
  • spring mvc declaring all beans singleton

这篇关于Spring bean如何处理并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆