多线程之ThreadLocal
Java并发编程:深入剖析ThreadLocal
想必很多朋友对ThreadLocal并不陌生,今天我们就来一起探讨下ThreadLocal的使用方法和实现原理。首先,本文先谈一下对ThreadLocal的理解,然后根据ThreadLocal类的源码分析了其实现原理和使用需要注意的地方,最后给出了两个应用场景。
以下是本文目录大纲:
一.对ThreadLocal的理解
二.深入解析ThreadLocal类
三.ThreadLocal的应用场景
若有不正之处请多多谅解,并欢迎批评指正。
请尊重作者劳动成果,转载请标明原文链接:
http://www.cnblogs.com/dolphin0520/p/3920407.html
一.对ThreadLocal的理解
ThreadLocal,很多地方叫做线程本地变量,也有些地方叫做线程本地存储,其实意思差不多。可能很多朋友都知道ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量。
这句话从字面上看起来很容易理解,但是真正理解并不是那么容易。
我们还是先来看一个例子:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | classConnectionManager {        privatestaticConnection connect = null;        publicstaticConnection openConnection() {        if(connect == null){            connect = DriverManager.getConnection();        }        returnconnect;    }        publicstaticvoidcloseConnection() {        if(connect!=null)            connect.close();    }} | 
假设有这样一个数据库链接管理类,这段代码在单线程中使用是没有任何问题的,但是如果在多线程中使用呢?很显然,在多线程中使用会存在线程安全问题:第一,这里面的2个方法都没有进行同步,很可能在openConnection方法中会多次创建connect;第二,由于connect是共享变量,那么必然在调用connect的地方需要使用到同步来保障线程安全,因为很可能一个线程在使用connect进行数据库操作,而另外一个线程调用closeConnection关闭链接。
所以出于线程安全的考虑,必须将这段代码的两个方法进行同步处理,并且在调用connect的地方需要进行同步处理。
这样将会大大影响程序执行效率,因为一个线程在使用connect进行数据库操作的时候,其他线程只有等待。
那么大家来仔细分析一下这个问题,这地方到底需不需要将connect变量进行共享?事实上,是不需要的。假如每个线程中都有一个connect变量,各个线程之间对connect变量的访问实际上是没有依赖关系的,即一个线程不需要关心其他线程是否对这个connect进行了修改的。
到这里,可能会有朋友想到,既然不需要在线程之间共享这个变量,可以直接这样处理,在每个需要使用数据库连接的方法中具体使用时才创建数据库链接,然后在方法调用完毕再释放这个连接。比如下面这样:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | classConnectionManager {        privateConnection connect = null;        publicConnection openConnection() {        if(connect == null){            connect = DriverManager.getConnection();        }        returnconnect;    }        publicvoidcloseConnection() {        if(connect!=null)            connect.close();    }}classDao{    publicvoidinsert() {        ConnectionManager connectionManager = newConnectionManager();        Connection connection = connectionManager.openConnection();                //使用connection进行操作                connectionManager.closeConnection();    }} | 
这样处理确实也没有任何问题,由于每次都是在方法内部创建的连接,那么线程之间自然不存在线程安全问题。但是这样会有一个致命的影响:导致服务器压力非常大,并且严重影响程序执行性能。由于在方法中需要频繁地开启和关闭数据库连接,这样不尽严重影响程序执行效率,还可能导致服务器压力巨大。
那么这种情况下使用ThreadLocal是再适合不过的了,因为ThreadLocal在每个线程中对该变量会创建一个副本,即每个线程内部都会有一个该变量,且在线程内部任何地方都可以使用,线程之间互不影响,这样一来就不存在线程安全问题,也不会严重影响程序执行性能。
但是要注意,虽然ThreadLocal能够解决上面说的问题,但是由于在每个线程中都创建了副本,所以要考虑它对资源的消耗,比如内存的占用会比不使用ThreadLocal要大。
二.深入解析ThreadLocal类
在上面谈到了对ThreadLocal的一些理解,那我们下面来看一下具体ThreadLocal是如何实现的。
先了解一下ThreadLocal类提供的几个方法:
| 1 2 3 4 | publicT get() { }publicvoidset(T value) { }publicvoidremove() { }protectedT initialValue() { } | 
get()方法是用来获取ThreadLocal在当前线程中保存的变量副本,set()用来设置当前线程中变量的副本,remove()用来移除当前线程中变量的副本,initialValue()是一个protected方法,一般是用来在使用时进行重写的,它是一个延迟加载方法,下面会详细说明。
首先我们来看一下ThreadLocal类是如何为每个线程创建一个变量的副本的。
先看下get方法的实现:
  
第一句是取得当前线程,然后通过getMap(t)方法获取到一个map,map的类型为ThreadLocalMap。然后接着下面获取到<key,value>键值对,注意这里获取键值对传进去的是 this,而不是当前线程t。
如果获取成功,则返回value值。
如果map为空,则调用setInitialValue方法返回value。
我们上面的每一句来仔细分析:
首先看一下getMap方法中做了什么:
  
可能大家没有想到的是,在getMap中,是调用当期线程t,返回当前线程t中的一个成员变量threadLocals。
那么我们继续取Thread类中取看一下成员变量threadLocals是什么:
  
实际上就是一个ThreadLocalMap,这个类型是ThreadLocal类的一个内部类,我们继续取看ThreadLocalMap的实现:
  
可以看到ThreadLocalMap的Entry继承了WeakReference,并且使用ThreadLocal作为键值。
然后再继续看setInitialValue方法的具体实现:

很容易了解,就是如果map不为空,就设置键值对,为空,再创建Map,看一下createMap的实现:
  
至此,可能大部分朋友已经明白了ThreadLocal是如何为每个线程创建变量的副本的:
首先,在每个线程Thread内部有一个ThreadLocal.ThreadLocalMap类型的成员变量threadLocals,这个threadLocals就是用来存储实际的变量副本的,键值为当前ThreadLocal变量,value为变量副本(即T类型的变量)。
初始时,在Thread里面,threadLocals为空,当通过ThreadLocal变量调用get()方法或者set()方法,就会对Thread类中的threadLocals进行初始化,并且以当前ThreadLocal变量为键值,以ThreadLocal要保存的副本变量为value,存到threadLocals。
然后在当前线程里面,如果要使用副本变量,就可以通过get方法在threadLocals里面查找。
下面通过一个例子来证明通过ThreadLocal能达到在每个线程中创建变量副本的效果:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | publicclassTest {    ThreadLocal<Long> longLocal = newThreadLocal<Long>();    ThreadLocal<String> stringLocal = newThreadLocal<String>();        publicvoidset() {        longLocal.set(Thread.currentThread().getId());        stringLocal.set(Thread.currentThread().getName());    }        publiclonggetLong() {        returnlongLocal.get();    }        publicString getString() {        returnstringLocal.get();    }        publicstaticvoidmain(String[] args) throwsInterruptedException {        finalTest test = newTest();                        test.set();        System.out.println(test.getLong());        System.out.println(test.getString());                    Thread thread1 = newThread(){            publicvoidrun() {                test.set();                System.out.println(test.getLong());                System.out.println(test.getString());            };        };        thread1.start();        thread1.join();                System.out.println(test.getLong());        System.out.println(test.getString());    }} | 
这段代码的输出结果为:
  
从这段代码的输出结果可以看出,在main线程中和thread1线程中,longLocal保存的副本值和stringLocal保存的副本值都不一样。最后一次在main线程再次打印副本值是为了证明在main线程中和thread1线程中的副本值确实是不同的。
总结一下:
1)实际的通过ThreadLocal创建的副本是存储在每个线程自己的threadLocals中的;
2)为何threadLocals的类型ThreadLocalMap的键值为ThreadLocal对象,因为每个线程中可有多个threadLocal变量,就像上面代码中的longLocal和stringLocal;
3)在进行get之前,必须先set,否则会报空指针异常;
如果想在get之前不需要调用set就能正常访问的话,必须重写initialValue()方法。
因为在上面的代码分析过程中,我们发现如果没有先set的话,即在map中查找不到对应的存储,则会通过调用setInitialValue方法返回i,而在setInitialValue方法中,有一个语句是T value = initialValue(), 而默认情况下,initialValue方法返回的是null。
  
看下面这个例子:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | publicclassTest {    ThreadLocal<Long> longLocal = newThreadLocal<Long>();    ThreadLocal<String> stringLocal = newThreadLocal<String>();    publicvoidset() {        longLocal.set(Thread.currentThread().getId());        stringLocal.set(Thread.currentThread().getName());    }        publiclonggetLong() {        returnlongLocal.get();    }        publicString getString() {        returnstringLocal.get();    }        publicstaticvoidmain(String[] args) throwsInterruptedException {        finalTest test = newTest();                System.out.println(test.getLong());        System.out.println(test.getString());        Thread thread1 = newThread(){            publicvoidrun() {                test.set();                System.out.println(test.getLong());                System.out.println(test.getString());            };        };        thread1.start();        thread1.join();                System.out.println(test.getLong());        System.out.println(test.getString());    }} | 
在main线程中,没有先set,直接get的话,运行时会报空指针异常。
但是如果改成下面这段代码,即重写了initialValue方法:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | publicclassTest {    ThreadLocal<Long> longLocal = newThreadLocal<Long>(){        protectedLong initialValue() {            returnThread.currentThread().getId();        };    };    ThreadLocal<String> stringLocal = newThreadLocal<String>(){;        protectedString initialValue() {            returnThread.currentThread().getName();        };    };        publicvoidset() {        longLocal.set(Thread.currentThread().getId());        stringLocal.set(Thread.currentThread().getName());    }        publiclonggetLong() {        returnlongLocal.get();    }        publicString getString() {        returnstringLocal.get();    }        publicstaticvoidmain(String[] args) throwsInterruptedException {        finalTest test = newTest();        test.set();        System.out.println(test.getLong());        System.out.println(test.getString());                    Thread thread1 = newThread(){            publicvoidrun() {                test.set();                System.out.println(test.getLong());                System.out.println(test.getString());            };        };        thread1.start();        thread1.join();                System.out.println(test.getLong());        System.out.println(test.getString());    }} | 
就可以直接不用先set而直接调用get了。
三.ThreadLocal的应用场景
最常见的ThreadLocal使用场景为 用来解决 数据库连接、Session管理等。
如:
| 1 2 3 4 5 6 7 8 9 10 | privatestaticThreadLocal<Connection> connectionHolder= newThreadLocal<Connection>() {publicConnection initialValue() {    returnDriverManager.getConnection(DB_URL);}};publicstaticConnection getConnection() {returnconnectionHolder.get();} | 
下面这段代码摘自:
http://www.iteye.com/topic/103804
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | privatestaticfinalThreadLocal threadSession = newThreadLocal();publicstaticSession getSession() throwsInfrastructureException {    Session s = (Session) threadSession.get();    try{        if(s == null) {            s = getSessionFactory().openSession();            threadSession.set(s);        }    } catch(HibernateException ex) {        thrownewInfrastructureException(ex);    }    returns;} | 
参考资料:
《深入理解Java虚拟机》
《Java编程思想》
http://ifeve.com/thread-management-10/
http://www.ibm.com/developerworks/cn/java/j-threads/index3.html
http://www.iteye.com/topic/103804
http://www.iteye.com/topic/777716
http://www.iteye.com/topic/757478
http://blog.csdn.net/ghsau/article/details/15732053
http://ispring.iteye.com/blog/162982
http://blog.csdn.net/imzoer/article/details/8262101
http://www.blogjava.net/wumi9527/archive/2010/09/10/331654.html
http://bbs.csdn.net/topics/380049261
多线程之ThreadLocal的更多相关文章
- 多线程之ThreadLocal类
		深入研究java.lang.ThreadLocal类 0.前言 ThreadLocal(线程变量副本)Synchronized实现内存共享,ThreadLocal为每个线程维护一个本地变量.采用空间换 ... 
- java多线程之ThreadLocal
		ThreadLocal为每个线程保存变量,以保证数据同步. package Thread.Common; import java.util.Random; import java.util.concu ... 
- 多线程之ThreadLocal(转)
		相信读者在网上也看了很多关于ThreadLocal的资料,很多博客都这样说:ThreadLocal为解决多线程程序的并发问题提供了一种新的思路:ThreadLocal的目的是为了解决多线程访问资源时的 ... 
- Java多线程之ThreadLocal总结2
		ThreadLocal是什么 早在JDK 1.2的版本中就提供Java.lang.ThreadLocal,ThreadLocal为解决多线程程序的并发问题提供了一种新的思路.使用这个工具类可以很简洁地 ... 
- Java多线程之ThreadLocal总结
		原贴地址:http://www.cnblogs.com/zhengbin/p/5674638.html 阅读目录 官方对ThreadLocal的描述: <Thinking in Java> ... 
- java基础---->多线程之ThreadLocal(七)
		这里学习一下java多线程中的关于ThreadLocal的用法.人时已尽,人世还长,我在中间,应该休息. ThreadLocal的简单实例 一.ThreadLocal的简单使用 package com ... 
- Java线程之ThreadLocal
		翻译:https://www.journaldev.com/1076/java-threadlocal-example?utm_source=website&utm_medium=sideba ... 
- 并发编程之ThreadLocal
		并发编程之ThreadLocal 前言 当多线程访问共享可变数据时,涉及到线程间同步的问题,并不是所有时候,都要用到共享数据,所以就需要线程封闭出场了. 数据都被封闭在各自的线程之中,就不需要同步,这 ... 
- iOS多线程之8.NSOPeration的其他用法
		本文主要对NSOPeration的一些重点属性和方法做出介绍,以便大家可以更好的使用NSOPeration. 1.添加依赖 - (void)addDependency:(NSOperation * ... 
随机推荐
- HTML5 Form Data 对象的使用
			HTML5 Form Data 对象的使用 MDN: https://developer.mozilla.org/zh-CN/docs/Web/Guide/Using_FormData_Object ... 
- vue+vux 父组件控制子组件弹层
			知识点用到了vue父子组件之间的传值,以及使用watch和v-model控制vux中XDialog组件. 需要注意的问题: 1.父组件向子组件传值使用的是props(单向传值),子组件创建props, ... 
- [HNOI2004]宠物收养场
			fhq treap 开俩哨兵节点,然后插入.删除.前驱.后继,统计即可 #include"cstdio" #include"cstring" #include& ... 
- How To Improve Deep Learning Performance
			如何提高深度学习性能 20 Tips, Tricks and Techniques That You Can Use ToFight Overfitting and Get Better Genera ... 
- Android Studio插件之MVPHelper,一键生成MVP代码
			MVP盛行,听到的最多的抱怨就是咋要写这么多接口,那么本文作者提供了一个插件,自动生成这些接口的声明.感兴趣的还可以学习该插件的写法,按照自己平时的需求修改,提供开发效率. MVPHelper 一款I ... 
- mac系统使用介绍
			点击左上角苹果-->关于本机 Dock-->偏好设置 推荐按装mac系统:OS X V10.8(山狮) Finder-->应用程序(安装程序)<==>我的电脑 Safar ... 
- Pwn with File结构体(三)
			前言 本文由 本人 首发于 先知安全技术社区: https://xianzhi.aliyun.com/forum/user/5274 前面介绍了几种 File 结构体的攻击方式,其中包括修改 vtab ... 
- Pwn With longjmp
			前言 这个是 seccon-ctf-quals-2016 的一个题,利用方式还是挺特殊的记录一下. 题目链接 http://t.cn/RnfeHLv 正文 首先看看程序的安全措施 haclh@ubun ... 
- Pig filter用法举例
			filter:过滤数据,只有符合特定条件的数据才会被保留下来,然后进入下一个数据流. 1)等值比较 filter data by $0 == 1 filter data by $0 != 1 ... 
- JQuery 选择器 筛选器
			什么是jQuery对象 参考:http://jquery.cuishifeng.cn/css.html jQuery 对象就是通过jQuery包装DOM对象后产生的对象.jQuery 对象是 jQue ... 
