资讯专栏INFORMATION COLUMN

(基础系列)ThreadLocal的用法、原理和用途

bitkylin / 1387人阅读

摘要:那线程局部变量就是每个线程都会有一个局部变量,独立于变量的初始化副本,而各个副本是通过线程唯一标识相关联的。移除此线程局部变量当前线程的值。如果此线程局部变量随后被当前线程读取,且这期间当前线程没有设置其值,则将调用其方法重新初始化其值。

前言

ThreadLocal网上资料很多,那我为什么还要写下这篇文章呢?主要是想汇聚多篇文章的优秀之处以及我对于ThreadLocal的理解来加深印象,也使读者能更全面的理解ThreadLocal的用法、原理和用途。

一、何谓“ThreadLocal”

</>复制代码

  1. ThreadLocal是一个线程局部变量,我们都知道全局变量和局部变量的区别,拿Java举例就是定义在类中的是全局的变量,各个方法中都能访问得到,而局部变量定义在方法中,只能在方法内访问。那线程局部变量(ThreadLocal)就是每个线程都会有一个局部变量,独立于变量的初始化副本,而各个副本是通过线程唯一标识相关联的。

二、ThreadLocal的用法

(1)方法摘要

作用域 类型 方法 描述
public T get() 返回此线程局部变量的当前线程副本中的值
protected T initialValue() 返回此线程局部变量的当前线程的“初始值”
public void remove() 移除此线程局部变量当前线程的值
public void set(T value) 将此线程局部变量的当前线程副本中的值设置为指定值

注意事项
==initialValue()== 这个方法是为了让子类覆盖设计的,默认缺省null。如果get()后又remove()则可能会在调用一下此方法。
==remove()== 移除此线程局部变量当前线程的值。如果此线程局部变量随后被当前线程 读取,且这期间当前线程没有 设置其值,则将调用其 initialValue() 方法重新初始化其值。这将导致在当前线程多次调用 initialValue 方法。

(2)常规用法

在开始之前贴出一个公共的线程测试类

</>复制代码

  1. public class TaskThread extends Thread{
  2. private T t;
  3. public TaskThread(String threadName,T t) {
  4. this.setName(threadName);
  5. this.t = t;
  6. }
  7. @Override
  8. public void run() {
  9. for (int i = 0; i < 2; i++) {
  10. try {
  11. Class[] argsClass = new Class[0];
  12. Method method = t.getClass().getMethod("getUniqueId",argsClass);
  13. int value = (int) method.invoke(t);
  14. System.out.println("thread[" + Thread.currentThread().getName() + "] --> uniqueId["+value+ "]");
  15. } catch (NoSuchMethodException e) {
  16. // TODO 暂不处理
  17. continue;
  18. } catch (IllegalAccessException e) {
  19. // TODO 暂不处理
  20. continue;
  21. } catch (InvocationTargetException e) {
  22. // TODO 暂不处理
  23. continue;
  24. }
  25. }
  26. }
  27. }

例1:为每个线程生成一个唯一的局部标识

</>复制代码

  1. public class UniqueThreadIdGenerator {
  2. // 原子整型
  3. private static final AtomicInteger uniqueId = new AtomicInteger(0);
  4. // 线程局部整型变量
  5. private static final ThreadLocal uniqueNum =
  6. new ThreadLocal < Integer > () {
  7. @Override protected Integer initialValue() {
  8. return uniqueId.getAndIncrement();
  9. }
  10. };
  11. //变量值
  12. public static int getUniqueId() {
  13. return uniqueId.get();
  14. }
  15. public static void main(String[] args) {
  16. UniqueThreadIdGenerator uniqueThreadId = new UniqueThreadIdGenerator();
  17. // 为每个线程生成一个唯一的局部标识
  18. TaskThread t1 = new TaskThread("custom-thread-1", uniqueThreadId);
  19. TaskThread t2 = new TaskThread("custom-thread-2", uniqueThreadId);
  20. TaskThread t3 = new TaskThread("custom-thread-3", uniqueThreadId);
  21. t1.start();
  22. t2.start();
  23. t3.start();
  24. }
  25. }

运行结果:

</>复制代码

  1. //每个线程的局部变量都是唯一的
  2. thread[custom-thread-2] --> uniqueId[0]
  3. thread[custom-thread-2] --> uniqueId[0]
  4. thread[custom-thread-1] --> uniqueId[0]
  5. thread[custom-thread-1] --> uniqueId[0]
  6. thread[custom-thread-3] --> uniqueId[0]
  7. thread[custom-thread-3] --> uniqueId[0]

例2:为每个线程创建一个局部唯一的序列

</>复制代码

  1. public class UniqueSequenceGenerator {
  2. // 线程局部整型变量
  3. private static final ThreadLocal uniqueNum =
  4. new ThreadLocal < Integer > () {
  5. @Override protected Integer initialValue() {
  6. return 0;
  7. }
  8. };
  9. //变量值
  10. public static int getUniqueId() {
  11. uniqueNum.set(uniqueNum.get() + 1);
  12. return uniqueNum.get();
  13. }
  14. public static void main(String[] args) {
  15. UniqueSequenceGenerator uniqueThreadId = new UniqueSequenceGenerator();
  16. // 为每个线程生成内部唯一的序列号
  17. TaskThread t1 = new TaskThread("custom-thread-1", uniqueThreadId);
  18. TaskThread t2 = new TaskThread("custom-thread-2", uniqueThreadId);
  19. TaskThread t3 = new TaskThread("custom-thread-3", uniqueThreadId);
  20. t1.start();
  21. t2.start();
  22. t3.start();
  23. }
  24. }

运行结果:

</>复制代码

  1. thread[custom-thread-2] --> uniqueId[1]
  2. thread[custom-thread-2] --> uniqueId[2]
  3. thread[custom-thread-1] --> uniqueId[1]
  4. thread[custom-thread-1] --> uniqueId[2]
  5. thread[custom-thread-3] --> uniqueId[1]
  6. thread[custom-thread-3] --> uniqueId[2]
三、ThreadLocal的原理(摘自网上)

(1)源码解析

源码实现片段:set

</>复制代码

  1. /**
  2. * Sets the current thread"s copy of this thread-local variable
  3. * to the specified value. Most subclasses will have no need to
  4. * override this method, relying solely on the {@link #initialValue}
  5. * method to set the values of thread-locals.
  6. *
  7. * @param value the value to be stored in the current thread"s copy of
  8. * this thread-local.
  9. */
  10. public void set(T value) {
  11. Thread t = Thread.currentThread();
  12. ThreadLocalMap map = getMap(t);
  13. if (map != null)
  14. map.set(this, value);
  15. else
  16. createMap(t, value);
  17. }

</>复制代码

  1. 在这个方法内部我们看到,首先通过getMap(Thread t)方法获取一个和当前线程相关的ThreadLocalMap,然后将变量的值设置到这个ThreadLocalMap对象中,当然如果获取到的ThreadLocalMap对象为空,就通过createMap方法创建。

  2. ==线程隔离的秘密,就在于ThreadLocalMap这个类。ThreadLocalMap是ThreadLocal类的一个静态内部类,它实现了键值对的设置和获取(对比Map对象来理解),每个线程中都有一个独立的ThreadLocalMap副本,它所存储的值,只能被当前线程读取和修改。ThreadLocal类通过操作每一个线程特有的ThreadLocalMap副本,从而实现了变量访问在不同线程中的隔离。因为每个线程的变量都是自己特有的,完全不会有并发错误。还有一点就是,ThreadLocalMap存储的键值对中的键是this对象指向的ThreadLocal对象,而值就是你所设置的对象了。== 这个就是实现原理

源码实现片段:getMap、createMap

</>复制代码

  1. /**
  2. * Get the map associated with a ThreadLocal. Overridden in
  3. * InheritableThreadLocal.
  4. *
  5. * @param t the current thread
  6. * @return the map
  7. */
  8. ThreadLocalMap getMap(Thread t) {
  9. return t.threadLocals;
  10. }
  11. /**
  12. * Create the map associated with a ThreadLocal. Overridden in
  13. * InheritableThreadLocal.
  14. *
  15. * @param t the current thread
  16. * @param firstValue value for the initial entry of the map
  17. * @param map the map to store.
  18. */
  19. void createMap(Thread t, T firstValue) {
  20. t.threadLocals = new ThreadLocalMap(this, firstValue);
  21. }

源码实现片段:get

</>复制代码

  1. /**
  2. * Returns the value in the current thread"s copy of this
  3. * thread-local variable. If the variable has no value for the
  4. * current thread, it is first initialized to the value returned
  5. * by an invocation of the {@link #initialValue} method.
  6. *
  7. * @return the current thread"s value of this thread-local
  8. */
  9. public T get() {
  10. Thread t = Thread.currentThread();
  11. ThreadLocalMap map = getMap(t);
  12. if (map != null) {
  13. ThreadLocalMap.Entry e = map.getEntry(this);
  14. if (e != null)
  15. return (T)e.value;
  16. }
  17. return setInitialValue();
  18. }

源码实现片段:setInitialValue

</>复制代码

  1. /**
  2. * Variant of set() to establish initialValue. Used instead
  3. * of set() in case user has overridden the set() method.
  4. *
  5. * @return the initial value
  6. */
  7. private T setInitialValue() {
  8. T value = initialValue();
  9. Thread t = Thread.currentThread();
  10. ThreadLocalMap map = getMap(t);
  11. if (map != null)
  12. map.set(this, value);
  13. else
  14. createMap(t, value);
  15. return value;
  16. }
  17. //获取和当前线程绑定的值时,ThreadLocalMap对象是以this指向的ThreadLocal对象为键
  18. //进行查找的,这当然和前面set()方法的代码是相呼应的。进一步地,我们可以创建不同的
  19. //ThreadLocal实例来实现多个变量在不同线程间的访问隔离,为什么可以这么做?因为不
  20. //同的ThreadLocal对象作为不同键,当然也可以在线程的ThreadLocalMap对象中设置不同
  21. //的值了。通过ThreadLocal对象,在多线程中共享一个值和多个值的区别,就像你在一个
  22. //HashMap对象中存储一个键值对和多个键值对一样,仅此而已。
四、ThreadLocal实际用途

例1:在数据库管理中的连接管理类是下面这样的:(摘自网上)

</>复制代码

  1. public class ConnectionManager {
  2. private static Connection connect = null;
  3. public static Connection getConnection() {
  4. if(connect == null){
  5. connect = DriverManager.getConnection();
  6. }
  7. return connect;
  8. }
  9. ...
  10. }

在单线程的情况下这样写并没有问题,但如果在多线程情况下回出现线程安全的问题。你可能会说用同步关键字或锁来保障线程安全,这样做当然是可行的,但考虑到性能的问题所以这样子做并是很优雅。
下面是改造后的代码:

</>复制代码

  1. public class ConnectionManager {
  2. private static ThreadLocal connThreadLocal = new ThreadLocal();
  3. public static Connection getConnection() {
  4. if(connThreadLocal.get() != null)
  5. return connThreadLocal.get();
  6. //获取一个连接并设置到当前线程变量中
  7. Connection conn = getConnection();
  8. connThreadLocal.set(conn);
  9. return conn;
  10. }
  11. ...
  12. }

例2:日期格式(摘自网上)

使用这个日期格式类主要作用就是将枚举对象转成Map而map的值则是使用ThreadLocal存储,那么在实际的开发中可以在同一线程中的不同方法中使用日期格式而无需在创建日期格式的实例。

</>复制代码

  1. public class DateFormatFactory {
  2. public enum DatePattern {
  3. TimePattern("yyyy-MM-dd HH:mm:ss"),
  4. DatePattern("yyyy-MM-dd");
  5. public String pattern;
  6. private DatePattern(String pattern) {
  7. this.pattern = pattern;
  8. }
  9. }
  10. private static final Map> pattern2ThreadLocal;
  11. static {
  12. DatePattern[] patterns = DatePattern.values();
  13. int len = patterns.length;
  14. pattern2ThreadLocal = new HashMap>(len);
  15. for (int i = 0; i < len; i++) {
  16. DatePattern datePattern = patterns[i];
  17. final String pattern = datePattern.pattern;
  18. pattern2ThreadLocal.put(datePattern, new ThreadLocal() {
  19. @Override
  20. protected DateFormat initialValue() {
  21. return new SimpleDateFormat(pattern);
  22. }
  23. });
  24. }
  25. }
  26. //获取DateFormat
  27. public static DateFormat getDateFormat(DatePattern pattern) {
  28. ThreadLocal threadDateFormat = pattern2ThreadLocal.get(pattern);
  29. //不需要判断threadDateFormat是否为空
  30. return threadDateFormat.get();
  31. }
  32. public static void main(String[] args) {
  33. String dateStr = DateFormatFactory.getDateFormat(DatePattern.TimePattern).format(new Date());
  34. System.out.println(dateStr);
  35. }
  36. }
五、总结

ThreadLocal是用冗余的方式换时间,而锁机制则是时间换空间,好的设计往往都是在时间、空间以及复杂度之间做权衡,道理是这样但是真正能平衡三者之间的人我姑且称之为“大成者”,愿你我在成长的道路上越走越远。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70472.html

相关文章

  • Java 总结

    摘要:中的详解必修个多线程问题总结个多线程问题总结有哪些源代码看了后让你收获很多,代码思维和能力有较大的提升有哪些源代码看了后让你收获很多,代码思维和能力有较大的提升开源的运行原理从虚拟机工作流程看运行原理。 自己实现集合框架 (三): 单链表的实现 自己实现集合框架 (三): 单链表的实现 基于 POI 封装 ExcelUtil 精简的 Excel 导入导出 由于 poi 本身只是针对于 ...

    caspar 评论0 收藏0
  • 七面阿里:现在分享一下阿里最全面试116题:阿里天猫、蚂蚁金服、阿里巴巴面试题含答案

    摘要:面试,是跳槽后第一个需要面对的问题而且不同公司面试的着重点不同但是却有一个共同点基础是必考的。对自动灾难恢复有要求的表。 貌似这一点适应的行业最广,但是我可以很肯定的说:当你从事Java一年后,重新找工作时,才会真实的感受到这句话。 工作第一年,往往是什么都充满新鲜感,什么都学习,冲劲十足的一年;WEB行业知识更新特别快,今天一个框架的新版本,明天又是另一个新框架,有时往往根据项目的需...

    animabear 评论0 收藏0
  • 七面阿里:现在分享一下阿里最全面试116题:阿里天猫、蚂蚁金服、阿里巴巴面试题含答案

    摘要:面试,是跳槽后第一个需要面对的问题而且不同公司面试的着重点不同但是却有一个共同点基础是必考的。对自动灾难恢复有要求的表。 貌似这一点适应的行业最广,但是我可以很肯定的说:当你从事Java一年后,重新找工作时,才会真实的感受到这句话。 工作第一年,往往是什么都充满新鲜感,什么都学习,冲劲十足的一年;WEB行业知识更新特别快,今天一个框架的新版本,明天又是另一个新框架,有时往往根据项目的需...

    fjcgreat 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<