使用Spring时经常会问,我们定义的Bean应该是Singleton还是Prototype?多个客户端同时调用Dao层,需要考虑线程安全吗?通过阅读官方文档和Spring的源代码,这类问题的答案是:自定义的Stateless Bean是不需要考虑线程安全问题的,可以在配置时设置为Singleton,减少new操作,提高程序效率;自定义的Stateful Bean是需要考虑线程安全问题的,Spring没有提供任何安全机制,只能由开发人员自己处理,比如使用ThreadLocal的方式或在配置时设置为Prototype。对于Dao层,Spring框架做了特殊处理。DataSource声明为Singleton模式,但其中的Connections是由支持线程安全的集合保存。与此同时,EntityManagerFactory是线程安全的,EntityManager不是,所以在每个Dao函数中都会首先执行:EntityManager entityManager = entityManagerFactory.createEntityManager()。如果追溯到最基本的JdbcTemplate用法,其官网的实例代码是:

 
public class JdbcCorporateEventDao implements CorporateEventDao {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
}
 

这表明每一个客户端调用都会产生一个新的JdbcTemplate对象,所以JdbcCorporateEventDao也就不会出现线程安全问题了。下面的代码是一个自定义的有状态Bean。程序运行结果表明,两个线程都在改变它的状态(成员变量),并且这种影响是不确定的。

 
package com.mmh.main;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mmh.printer.PrintHelper; public class Application { public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"appContext.xml"); ExecutorService executors = Executors.newCachedThreadPool(); executors.execute(new PrintThread(context));
executors.execute(new PrintThread(context));
}
} class PrintThread implements Runnable { private ApplicationContext context; public PrintThread(ApplicationContext context) {
this.context = context;
} public void run() {
PrintHelper printHelper = context.getBean(PrintHelper.class); try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
} for (int i = 0; i < 2; i++) {
printHelper.print();
printHelper.increamentYears();
}
}
}
// 输出结果:
/*
* Thread[pool-1-thread-1,5,main]: yzp---28
* Thread[pool-1-thread-2,5,main]: yzp---28
* Thread[pool-1-thread-2,5,main]: yzp---30
* Thread[pool-1-thread-1,5,main]: yzp---29
*/
 

  把自定义Bean的scope设定为:prototype,程序运行结果表明,它的状态没有被两个线程相互干扰。

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="printHelper" class="com.mmh.printer.PrintHelper" scope="prototype">
<constructor-arg index="0" value="yzp"/>
<constructor-arg index="1" value="28"/>
</bean> </beans>
 
 
// 输出结果:
/*
* Thread[pool-1-thread-1,5,main]: yzp---28
* Thread[pool-1-thread-1,5,main]: yzp---29
* Thread[pool-1-thread-2,5,main]: yzp---28
* Thread[pool-1-thread-2,5,main]: yzp---29
*/
 

  在debug时跟踪代码可以看到,IoC容器初始化时会创建一个注册类DefaultSingletonBeanRegistry,在这个类里有这样一行代码:private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64),其中的singletonObjects就是保存SingletonBean的集合,它的类型是ConcurrentHashMap,该集合本身支持线程安全。下面的代码是Spring的源代码,getBean()获取SingletonBean的核心内容。

 
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
 

如果singletonObjects中有需要的Bean,就直接取出来返回,如果没有,那么在同步块中使用ObjectFactory创建一个新的Bean。由代码可以看到,无论是直接获取还是新创建,操作过程都是线程安全的。

Threads in Spring的更多相关文章

  1. java 和 spring 的异步

    spring 的 async 注解 https://www.baeldung.com/spring-async@Async will make it execute in a separate thr ...

  2. SpringBoot开发案例之整合Dubbo分布式服务

    前言 在 SpringBoot 很火热的时候,阿里巴巴的分布式框架 Dubbo 不知是处于什么考虑,在停更N年之后终于进行维护了.在之前的微服务中,使用的是当当维护的版本 Dubbox,整合方式也是使 ...

  3. multi-threads JavaEE 容器

    Thread -- Request What is recommended way for spawning threads from a servlet in Tomcat [duplicate] ...

  4. Session挂起

    异常信息: toString() unavailable - no suspended threads 使用Spring管理 ,在使用hibernate时使用如下语句Session session = ...

  5. Spring webapp - shutting down threads on Application stop

    显示使用线程池Executors,必须执行 pool.shutdown() 否则会存在线程池泄露: http://stackoverflow.com/questions/22650569/spring ...

  6. Spring cache简单使用guava cache

    Spring cache简单使用 前言 spring有一套和各种缓存的集成方式.类似于sl4j,你可以选择log框架实现,也一样可以实现缓存实现,比如ehcache,guava cache. [TOC ...

  7. 第一个Spring Boot Web程序

    需要的环境和工具: 1.Eclipse2.Java环境(JDK 1.7或以上版本)3.Maven 3.0+(Eclipse已经内置了) 写个Hello Spring: 1.新建一个Maven项目,项目 ...

  8. Spring boot配置文件 application.properties

    http://www.tuicool.com/articles/veUjQba 本文记录Spring Boot application.propertis配置文件的相关通用属性 # ========= ...

  9. Spring MVC 学习总结(三)——请求处理方法Action详解

    Spring MVC中每个控制器中可以定义多个请求处理方法,我们把这种请求处理方法简称为Action,每个请求处理方法可以有多个不同的参数,以及一个多种类型的返回结果. 一.Action参数类型 如果 ...

随机推荐

  1. delphi 读取excel 两种方法

    http://www.cnblogs.com/ywangzi/archive/2012/09/27/2705894.html 两种方法,一是用ADO连接,问题是Excel文件内容要规则,二是用OLE打 ...

  2. R语言书籍的学习路线图

    现在对R感兴趣的人越来越多,很多人都想快速的掌握R语言,然而,由于目前大部分高校都没有开设R语言课程,这就导致很多人不知道如何着手学习R语言. 对于初学R语言的人,最常见的方式是:遇到不会的地方,就跑 ...

  3. 《zw版·delphi与halcon系列原创教程》zw版_THOperatorSetX控件函数列表 v11中文增强版

    <zw版·delphi与halcon系列原创教程>zw版_THOperatorSetX控件函数列表v11中文增强版 Halcon虽然庞大,光HALCONXLib_TLB.pas文件,源码就 ...

  4. php防sql注入

    [一.在服务器端配置] 安全,PHP代码编写是一方面,PHP的配置更是非常关键. 我 们php手手工安装的,php的默认配置文件在 /usr/local/apache2/conf/php.ini,我们 ...

  5. yii2验证码的使用

    1.控制器中 public function actions()     {         return [             'captcha' => [               ...

  6. Mysql子查询、关联查询

    mysql中update.delete.install尽量不要使用子查询 一.mysql查询的五种子句         where(条件查询).having(筛选).group by(分组).orde ...

  7. 对Alexia(minmin)网友代码的评论及对“求比指定数大且最小的‘不重复数’问题”代码的改进

    应Alexia(minmin)网友之邀,到她的博客上看了一下她的关于“求比指定数大且最小的‘不重复数’问题”的代码(百度2014研发类校园招聘笔试题解答),并在评论中粗略地发表了点意见. 由于感觉有些 ...

  8. Connection termination(by client)” 错误的处理方法

    背景: 在一些项目,当我们使用LR录制脚本的时候,在我们安装认证我们无法启动[网址= ] HTTPS [/url]的IE插件,页面显示空白,没有事件的记录,在Firefox也一样. 在记录日志,我们会 ...

  9. delphi 与 C++的基本语法区别

    [1]“=”符号 (1)“=”作为比较符.但是,当定义const常量时,“=”又表示赋值符号.而“:=”作为赋值符号. (2)“=”只表示赋值符号 [2]结构体 (1)record 作为结构体 (2) ...

  10. 【python cookbook】【数据结构与算法】6.在字典中将键映射到多个值上

    问题:一个能将键(key)映射到多个值的字典(即所谓的一键多值字典[multidict]) 解决方案:如果想让键映射到多值,需要将这多个值保持到另一个容器如列表或集合中: >>> d ...