threadLocal是要解决什么问题?在什么比例的应用解决问题场景下使用呢

threadLocal是要解决什么问题?在什么应用场景下使用呢_百度知道
threadLocal是要解决什么问题?在什么应用场景下使用呢
ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了线程保持对象的方法和避免参数传递的方便的对象访问方式
知道智能回答机器人
我是知道站内的人工智能,可高效智能地为您解答问题。很高兴为您服务。
其他类似问题
为您推荐:
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁新功能即将推出近来参与一个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();
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
三、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.
* 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 = nextHashC
nextHashCode = h + HASH_INCREMENT;
* 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);
* 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);
createMap(t, value);
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
t the current thread
* @return the map
ThreadLocalMap getMap(Thread t) {
return t.threadL
* 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 =
0x1.深入研究java.lang.ThreadLocal类
0x2.正确理解ThreadLocal
阅读(...) 评论()threadLocal是要解决什么问题?在什么应用场景下使用呢_百度知道
threadLocal是要解决什么问题?在什么应用场景下使用呢
ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了线程保持对象的方法和避免参数传递的方便的对象访问方式
彩虹在线,送给父母的礼物!
主营:通讯设备、产品、电脑、平板硬件和软件开发,手机应用
其他类似问题
为您推荐:
threadlocal的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁java(17)
说明ThreadLocal的用法和运用场景
主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。
首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。
另外,说ThreadLocal使得各线程能够保持各自独立的一个对象,并不是通过ThreadLocal.set()来实现的,而是通过每个线程中的new 对象操作来创建的对象,每个线程创建一个,不是什么对象的拷贝或副本。通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象,ThreadLocal实例是作为map的key来使用的。
如果ThreadLocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的ThreadLocal.get()取得的还是这个共享对象本身,还是有并发访问问题。
下面来看一个hibernate中典型的ThreadLocal的应用:
private static final ThreadLocal threadSession = new ThreadLocal();
public static Session getSession() throws InfrastructureException {
Session s = (Session) threadSession.get();
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
可以看到在getSession()方法中,首先判断当前线程中有没有放进去session,如果还没有,那么通过sessionFactory().openSession()来创建一个session,再将session set到线程中,实际是放到当前线程的ThreadLocalMap这个map中,这时,对于这个session的唯一引用就是当前线程中的那个ThreadLocalMap(下面会讲到),而threadSession作为这个值的key,要取得这个session可以通过threadSession.get()来得到,里面执行的操作实际是先取得当前线程中的ThreadLocalMap,然后将threadSession作为key将对应的值取出。这个session相当于线程的私有变量,而不是public的。
显然,其他线程中是取不到这个session的,他们也只能取到自己的ThreadLocalMap中的东西。要是session是多个线程共享使用的,那还不乱套了。
总之,ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。
归纳了两点:
1。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。
2。将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
当然如果要把本来线程共享的对象通过ThreadLocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。
ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:5337次
排名:千里之外
原创:19篇
转载:25篇
(1)(5)(1)(1)(1)(2)(2)(5)(3)(11)(9)(2)(1)

我要回帖

更多关于 threadlocal 性能问题 的文章

 

随机推荐