一个错误使用单例模式的场景及ThreadLocal简析
近来参与一个Java的web办公系统,碰到一个bug,开始猜测是线程池管理的问题,最后发现是单例模式的问题。
即,当同时发起两个事务请求时,当一个事务完成后,另一个事务会抛出session is closed异常。具体见下图:

至于,下面这种情况,当时也测试过,但问题情形忘了,手上没有数据库环境,无法进行测试:

最开始,个人认为是session管理的问题,比如,在关闭session的时候,会同时关闭先前打开的session。由于下面采用的是其他公司的框架,所以就反馈给了技术总监。后来,反馈给我,竟然是单例的问题。
简单看了一下本系统,其在框架基础上又封装了一层,涉及这个bug的类关系如下:

发现原来设想复杂了,本框架并没有一个session的线程池管理,仅仅是对每个请求新建一个ThreadLocal对象(在DaoFactoryClass中实现),其中的initValue方法中新建了一个session对象。
问题出现在自己封装的DaoBaseClass类中,此类实现了一个单例模式,需要一个Dao参数,这个参数是通过ActionFrameClass的方法getDao()获得的,于是乎,原来实现的每个线程一个session变量,现在又被单例模式给破坏了。
附注:
ThreadLocal和Synchonized都用于解决多线程并发访问。但是ThreadLocal与synchronized有本质的区别。synchronized是利用锁的机制,使变量或代码块在某一时该只能被一个线程访问。而ThreadLocal为每一个线程都提供了变量的副本,使得每个线程在某一时间访问到的并不是同一个对象,这样就隔离了多个线程对数据的数据共享。而Synchronized却正好相反,它用于在多个线程间通信时能够获得数据共享。
Synchronized用于线程间的数据共享,而ThreadLocal则用于线程间的数据隔离。
一、ThreadLocal使用一般步骤:
1、在多线程的类(如ThreadDemo类)中,创建一个ThreadLocal对象threadXxx,用来保存线程间需要隔离处理的对象xxx。
2、在ThreadDemo类中,创建一个获取要隔离访问的数据的方法getXxx(),在方法中判断,若ThreadLocal对象为null时候,应该new()一个隔离访问类型的对象,并强制转换为要应用的类型。
3、在ThreadDemo类的run()方法中,通过getXxx()方法获取要操作的数据,这样可以保证每个线程对应一个数据对象,在任何时刻都操作的是这个对象。
二、Hibernate中的使用:
private static final ThreadLocal threadSession = new ThreadLocal();
public static Session getSession() throws InfrastructureException { Session s = (Session) threadSession.get(); try { if (s == null) { s = getSessionFactory().openSession(); threadSession.set(s); } } catch (HibernateException ex) { throw new InfrastructureException(ex); } return s; }
三、ThreadLocal实现原理(JDK1.5中)
public class ThreadLocal<T> { /** * ThreadLocals rely on per-thread hash maps attached to each thread * (Thread.threadLocals and inheritableThreadLocals). The ThreadLocal * objects act as keys, searched via threadLocalHashCode. This is a * custom hash code (useful only within ThreadLocalMaps) that eliminates * collisions in the common case where consecutively constructed * ThreadLocals are used by the same threads, while remaining well-behaved * in less common cases. */ private final int threadLocalHashCode = nextHashCode();
/** * The next hash code to be given out. Accessed only by like-named method. */ private static int nextHashCode = 0;
/** * The difference between successively generated hash codes - turns * implicit sequential thread-local IDs into near-optimally spread * multiplicative hash values for power-of-two-sized tables. */ private static final int HASH_INCREMENT = 0x61c88647;
/** * Compute the next hash code. The static synchronization used here * should not be a performance bottleneck. When ThreadLocals are * generated in different threads at a fast enough rate to regularly * contend on this lock, memory contention is by far a more serious * problem than lock contention. */ private static synchronized int nextHashCode() { int h = nextHashCode; nextHashCode = h + HASH_INCREMENT; return h; }
/** * Creates a thread local variable. */ public ThreadLocal() { }
/** * Returns the value in the current thread's copy of this thread-local * variable. Creates and initializes the copy if this is the first time * the thread has called this method. * * @return the current thread's value of this thread-local */ public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) return (T)map.get(this);
// Maps are constructed lazily. if the map for this thread // doesn't exist, create it, with this ThreadLocal and its // initial value as its only entry. T value = initialValue(); createMap(t, value); return value; }
/** * Sets the current thread's copy of this thread-local variable * to the specified value. Many applications will have no need for * this functionality, relying solely on the {@link #initialValue} * method to set the values of thread-locals. * * @param value the value to be stored in the current threads' copy of * this thread-local. */ public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
/** * Get the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @return the map */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
/** * Create the map associated with a ThreadLocal. Overridden in * InheritableThreadLocal. * * @param t the current thread * @param firstValue value for the initial entry of the map * @param map the map to store. */ void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
.......
/** * ThreadLocalMap is a customized hash map suitable only for * maintaining thread local values. No operations are exported * outside of the ThreadLocal class. The class is package private to * allow declaration of fields in class Thread. To help deal with * very large and long-lived usages, the hash table entries use * WeakReferences for keys. However, since reference queues are not * used, stale entries are guaranteed to be removed only when * the table starts running out of space. */ static class ThreadLocalMap {
........
}
}
public class Thread implements Runnable { ......
/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; ...... }
一个错误使用单例模式的场景及ThreadLocal简析的更多相关文章
- ThreadLocal简析
简介 ThreadLocal在Java多线程开发中常见的一个类,在面试中也经见的问题,比如ThreadLocal的作用是什么,ThreadLocal的实现原理是什么等等.ThreadLocal是jav ...
- 关于Java中的继承和组合的一个错误使用的例子
[TOC] 关于Java中的继承和组合的一个错误使用的例子 相信绝大多数人都比较熟悉Java中的「继承」和「组合」这两个东西,本篇文章就主要就这两个话题谈论一下.如果我某些地方写的不对,或者比较幼稚, ...
- 「设计模式」JavaScript - 设计模式之单例模式与场景实践
单例介绍 上次总结了设计模式中的module模式,可能没有真真正正的使用在场景中,发现效果并不好,想要使用起来却不那么得心应手, 所以这次我打算换一种方式~~从简单的场景中来看单例模式, 因为Java ...
- C#反序列化XML异常:在 XML文档(0, 0)中有一个错误“缺少根元素”
Q: 在反序列化 Xml 字符串为 Xml 对象时,抛出如下异常. 即在 XML文档(0, 0)中有一个错误:缺少根元素. A: 首先看下代码: StringBuilder sb = new Stri ...
- 每天一个设计模式-4 单例模式(Singleton)
每天一个设计模式-4 单例模式(Singleton) 1.实际生活的例子 有一天,你的自行车的某个螺丝钉松了,修车铺离你家比较远,而附近的五金店有卖扳手:因此,你决定去五金店买一个扳手,自己把螺丝钉固 ...
- 处理程序“ExtensionlessUrlHandler-Integrated-4.0”在其模块列表中有一个错误模块“ManagedPipelineHandler”
新服务器安装完开发环境后,还需要注册framework4.0到IIS.不然会报错: HTTP 错误 500.21 - Internal Server Error 处理程序“Extensionles ...
- HTTP 错误 500.21 - Internal Server Error 处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”
HTTP 错误 500.21 - Internal Server Error 处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipe ...
- 【ASP.NET 问题】IIS发布网站后出现 "处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误"的解决办法
新装IIS,然后发布网站,运行出现如下错误提示 处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler” 于是 ...
- asp.net发布到IIS中出现错误:处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”
asp.net发布到IIS中出现错误:处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler” http:// ...
随机推荐
- python3知识点之---------字符串的介绍
1. 定义 其实字符串就是一系列字符,用引号括起来的就是字符串,其中的引号可以是单引号或者双引号. 比如 "This is a string" 'This is a strin ...
- GBDT(梯度提升树)scikit-klearn中的参数说明及简汇
1.GBDT(梯度提升树)概述: GBDT是集成学习Boosting家族的成员,区别于Adaboosting.adaboosting是利用前一次迭代弱学习器的误差率来更新训练集的权重,在对更新权重后的 ...
- Python——初识Python
本篇主要内容: • Python的特点 • Python的种类 • Python的编码 • Python的安装环境推荐 • Python的基础用法:输入输出,算术运算符,逻辑运算符,基本程序结构语法 ...
- CentOS 6.3 下 vsftp搭建
环境:CentOS6.3 ftp的三种用户模式 匿名用户:vsftp默认开启匿名用户,但只允许下载不允许上传:匿名用户anonymous或ftp:匿名用户目录/var/ftp,但实际上vsftp对匿名 ...
- bash语法注意点
bash 语法注意点 =和不能分开 如: val=expr $a + $b` [空格 *** 空格]条件判断要有空格 如: if [ $a ==$b ] 表达式和运算符之间要有空格, $a空格 + 空 ...
- C#中的&运算
2是一个比较特殊的数. 2的1次方2 2的2次方4 2的3次方8 2的4次方16 2的5次方32 2的6次方64 2的7次方128 2的8次方256 2的9次方512 2的10次方1024 2的11次 ...
- 【Android】实验3 颜色、字符串资源的使用【提交截止时间:2016.4.1】
实验4 颜色.字符串资源的使用 [目的] 掌握Android中颜色和字符串资源的使用方法. 理解Android中尺寸和布局资源的使用方法. [要求] 在工程中为Activity.View使用颜色资源: ...
- Redux & React & react-redux
Redux Redux & React & react-redux https://redux.js.org/ https://redux.js.org/api https://red ...
- P2135 方块消除
题目描述 Jimmy最近迷上了一款叫做方块消除的游戏.游戏规则如下:n个带颜色方格排成一列,相同颜色的方块连成一个区域(如果两个相邻方块颜色相同,则这两个方块属于同一区域).为简化题目,将连起来的同一 ...
- 【POJ3415】 Common Substrings (SA+单调栈)
这道是求长度不小于 k 的公共子串的个数...很不幸,我又TLE了... 解法参考论文以及下面的链接 http://www.cnblogs.com/vongang/archive/2012/11/20 ...