当同时访问多个Spring Singleton实例时 [英] When multiple access Spring Singleton instance at same time

查看:156
本文介绍了当同时访问多个Spring Singleton实例时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在spring config中的singleton范围内定义服务,如果多个用户尝试同时访问它(即作为依赖注入到您的控制器中),会发生什么?应该引起任何冲突吗?还是IoC容器将保留以后的调用,直到第一个调用完成?如果是这样的话,它会降低大型应用程序的性能,这对我来说不合适.有人可以给我一个正确的答案吗?

If you define your service in singleton scope in your spring config, what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time? Should it cause any conflict? Or the IoC container will hold the later call until the first one finish? If so it should slow down the performance in large applications, which sounds not right to me. Could any one give me a correct answer?

BTW,如果它不是单例的,则IoC容器将根据请求数来池化几个实例.有人可以确认吗?

BTW, as I can remember, if it is not a singleton one, IoC container will pool few instances based on the number of requests. Could some one confirm it?

推荐答案

如果一个以上的用户尝试同时访问它(例如,作为依赖项注入到您的控制器中),将会发生什么?

what would happen if more than one user try to access it (ie as dependency injected into your controller) at the same time?

一个单例bean可以同时访问很多次.这就是为什么它必须始终是线程安全的

A singleton bean can be accessed many times concurrently. That's why it always has to be thread-safe

应该引起任何冲突吗?

Should it cause any conflict?

仅当您无法使其成为线程安全的

Only if you fail to make it thread-safe

还是IoC容器将保留以后的调用,直到第一个调用结束?

Or the IoC container will hold the later call until the first one finish?

不,那太可怕了

我记得,

BTW,如果它不是单例的,则IoC容器将根据请求数来池化几个实例.有人可以确认吗?

BTW, as I can remember, if it is not a singleton one, IoC container will pool few instances based on the number of requests. Could some one confirm it?

Spring具有以下范围(请参阅Bean范围参考):

Spring has the following scopes (see Bean Scopes reference):

  • 全局会话(每个全局HTTP会话一个实例,仅在基于Portlet的Spring MVC中)
  • singleton (only one instance is managed per application)
  • prototype (a new instance for every injection)
  • session (one instance per HTTP session, only in Spring MVC)
  • request (one instance per HTTP request, only in Spring MVC)
  • global session (one instance per global HTTP session, only in portlet-based Spring MVC)

也:

从Spring 3.0开始,线程作用域可用,但默认情况下未注册.有关更多信息,请参见您描述的是一个对象池.在Spring中,它将作为原型范围的 Apache Commons/Pool 之类的库.

What you describe is an Object Pool. In Spring that would be implemented as a Prototype-scoped FactoryBean. And internally it would use a library like Apache Commons / Pool.

这篇关于当同时访问多个Spring Singleton实例时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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