Spring单例Bean和线程安全

  • Post author:
  • Post category:其他





Spring的bean默认都是单例的,这些单例Bean在多线程程序下如何保证线程安全呢?例如对于Web应用来说,Web容器对于每个用户请求都创建一个单独的Sevlet线程来处理请求,引入Spring框架之后,每个Action都是单例的,那么对于Spring托管的单例Service Bean,如何保证其安全呢?本文介绍了以上的安全问题。


Spring的原型Bean与单例Bean

的设置


spring单例Bean



spring

中的Bean缺省的情况下是单例模式的,在

spring容器

中分配Bean的时候(无论通过getBean()还是通过依赖注入(IOC)),它总是返回同一个Bean的实例,如果你想每次向上下文请求一个bean的时候总是得到一个不同的实例,或者想每次想从

spring容器

中得到一个bean的不同实例,需要将bean定义为原型模式,定义为原型模式意味着你是定义一个bean的类,而不是一个单一的bean的实例,bean的实例都是按照这个类而创建的。


spring原型Bean


在spring中<bean>的singleton属性告诉上下文这个bean是原型bean或者是单例bean。bean的缺省值为 true,如果设为false的话,就把这个bean定义成了原型bean。例如:<beanid=”test” class=”demo.Demo” singleton=”false” />

在spring2.x中<bean id=”test”scope=”prototype”/>将这样配置,但是如果想使用spring的原型bean必须通过getBean(”test”)这样的方 式,而不能通过使用IOC方式,因为:getBean将每次都有spring来装配转发,而IOC将只是一次注入的目标bean中,以后不再重新注入。这 样通过getBean方式将得到一个原型bean。如果bean使用的是有限资源,如数据库和网络链接的话不需要使用原型bean,正常不要把 singleton=”false”或者scope=”prototype”除非必要。

Spring 单例Bean和Java 单例模式的区别

Spring的的单例是基于BeanFactory也就是spring容器,单例Bean在此Spring容器内是单个的,Java的单例是基于JVM,每个JVM内一个单例。

线程安全


Thread safety

is a

computer programming

concept applicable in thecontext of

multi-threaded

programs. A piece of codeis

thread-safe

if it can be safely invoked by multiple threads at thesame time


[1]


.

Thread safety is a key challenge in multi-threadedprogramming. It was not a concern for most application programmers of littlehome applications, but since the 1990s, as Windows became multithreaded, andwith the expansion of BSD and Linux operating systems, it has become acommonplace issue. In a multi-threaded program, several threads executesimultaneously in a shared

address space

. Every thread has access to virtuallyall the

memory

of every other thread. Thus the flow ofcontrol and the sequence of accesses to data often have little relation to whatwould be reasonably expected by looking at the text of the program, violatingthe

principle of least astonishment

.Thread safety is a property that allows code to run in multi-threadedenvironments by re-establishing some of the correspondences between the actualflow of control and the text of the program, by means of

Process synchronization

.

Identification

It is not easy to determine if a piece of code isthread-safe or not. However, there are several indicators that suggest the needfor careful examination to see if it is



版权声明:本文为xiaojianpitt原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。