How does Spring bean Handle concurrency

﹥>﹥吖頭↗ 提交于 2019-12-18 10:42:25

问题


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 methods will access the same spring bean concurrently.

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?


回答1:


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.

See also:

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



回答2:


If the bean is a singleton, then Spring will give you the same instance in any thread. It's up to you to make that bean thread-safe. Since it's a singleton, you'd be best off making that class stateless.




回答3:


As others have already suggested, Spring is going to provide the same instance to all the threads in case of "singleton" beans.

What you need to understand is that threads do all the work in a system by executing the code while objects provide state and behavior (code). So it is indeed possible for multiple threads (requests in your case), to be concurrently running same methods in a singleton bean. You can either make such beans stateless as Tomasz suggested or otherwise make them "thread-safe".




回答4:


Java singleton and spring singleton are different. Spring singleton scope will be available within context.

Java singleton scope will be in JVM class loader. Hence concurrent request possible only through spring contexts



来源:https://stackoverflow.com/questions/13776728/how-does-spring-bean-handle-concurrency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!