之前面试的时候问到ThreadLocal老是一脸懵逼,只知道有这个哥们,不了解他是用来作什么的,更不清楚他的原理了。表面上看他是和多线程,线程同步有关的一个工具类,但其实他与线程同步机制无关。java
线程同步机制是多个线程共享同一个变量,而ThreadLocal是为每一个线程建立一个单独的变量副本,每一个线程均可以改变本身的变量副本而不影响其它线程所对应的副本。面试
官方API上是这样介绍的:api
该类提供了线程局部(thread-local)变量。这些变量不一样于它们的普通对应物,由于访问某个变量(经过其 get 或 set 方法)的每一个线程都有本身的局部变量,它独立于变量的初始化副本。ThreadLocal实例一般是类中的 private static 字段,它们但愿将状态与某一个线程(例如,用户 ID 或事务 ID)相关联。数组
ThreadLocal定义了四个方法:安全
ThreadLocal还有一个特别重要的静态内部类ThreadLocalMap,该类才是实现线程隔离机制的关键。get()、set()、remove()都是基于该内部类进行操做,ThreadLocalMap用键值对方式存储每一个线程变量的副本,key为当前的ThreadLocal对象,value为对应线程的变量副本。多线程
试想,每一个线程都有本身的ThreadLocal对象,也就是都有本身的ThreadLocalMap,对本身的ThreadLocalMap操做,固然是互不影响的了,这就不存在线程安全问题了,因此ThreadLocal是以空间来交换安全性的解决思路。ide
假设每一个线程都须要一个计数值记录本身作某件事作了多少次,各线程运行时都须要改变本身的计数值并且相互不影响,那么ThreadLocal就是很好的选择,这里ThreadLocal里保存的当前线程的局部变量的副本就是这个计数值。工具
public class SeqCount { private static ThreadLocal<Integer> seqCount = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return 0; } }; public int nextSeq() { seqCount.set(seqCount.get() +1); return seqCount.get(); } public static void main(String [] args) { SeqCount seqCount = new SeqCount(); SeqThread seqThread1 = new SeqThread(seqCount); SeqThread seqThread2 = new SeqThread(seqCount); SeqThread seqThread3 = new SeqThread(seqCount); SeqThread seqThread4 = new SeqThread(seqCount); seqThread1.start(); seqThread2.start(); seqThread3.start(); seqThread4.start(); } public static class SeqThread extends Thread { private SeqCount seqCount; public SeqThread(SeqCount seqCount) { this.seqCount = seqCount; } @Override public void run() { for (int i=0; i<3; i++) { System.out.println(Thread.currentThread().getName()+" seqCount:"+seqCount.nextSeq()); } } } }
运行结果:
源码分析
咱们知道SimpleDateFormat在多线程下是存在线程安全问题的,那么将SimpleDateFormat做为每一个线程的局部变量的副本就是每一个线程都拥有本身的SimpleDateFormat,就不存在线程安全问题了。this
public class SimpleDateFormatDemo { private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<>(); /** * 获取线程的变量副本,若是不覆盖initialValue方法,第一次get将返回null,故须要建立一个DateFormat,放入threadLocal中 * @return */ public DateFormat getDateFormat() { DateFormat df = threadLocal.get(); if (df == null) { df = new SimpleDateFormat(DATE_FORMAT); threadLocal.set(df); } return df; } public static void main(String [] args) { SimpleDateFormatDemo formatDemo = new SimpleDateFormatDemo(); MyRunnable myRunnable1 = new MyRunnable(formatDemo); MyRunnable myRunnable2 = new MyRunnable(formatDemo); MyRunnable myRunnable3 = new MyRunnable(formatDemo); Thread thread1= new Thread(myRunnable1); Thread thread2= new Thread(myRunnable2); Thread thread3= new Thread(myRunnable3); thread1.start(); thread2.start(); thread3.start(); } public static class MyRunnable implements Runnable { private SimpleDateFormatDemo dateFormatDemo; public MyRunnable(SimpleDateFormatDemo dateFormatDemo) { this.dateFormatDemo = dateFormatDemo; } @Override public void run() { System.out.println(Thread.currentThread().getName()+" 当前时间:"+dateFormatDemo.getDateFormat().format(new Date())); } } }
运行结果:
ThreadLocalMap内部是利用Entry来进行key-value的存储的。
static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }
上面源码中key就是ThreadLocal,value就是值,Entry继承WeakReference,因此Entry对应key的引用(ThreadLocal实例)是一个弱引用。
/** * Set the value associated with key. * * @param key the thread local object * @param value the value to be set */ private void set(ThreadLocal<?> key, Object value) { Entry[] tab = table; int len = tab.length; //根据ThreadLocal的散列值,查找对应元素在数组中的位置 int i = key.threadLocalHashCode & (len-1); //采用线性探测法寻找合适位置 for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) { ThreadLocal<?> k = e.get(); //key存在,直接覆盖 if (k == key) { e.value = value; return; } // key == null,可是存在值(由于此处的e != null),说明以前的ThreadLocal对象已经被回收了 if (k == null) { replaceStaleEntry(key, value, i); return; } } //ThreadLocal对应的key实例不存在,new一个 tab[i] = new Entry(key, value); int sz = ++size; //清楚陈旧的Entry(key == null的) // 若是没有清理陈旧的 Entry 而且数组中的元素大于了阈值,则进行 rehash if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); }
这个set操做和集合Map解决散列冲突的方法不一样,集合Map采用的是链地址法,这里采用的是开放定址法(线性探测)。set()方法中的replaceStaleEntry()和cleanSomeSlots(),这两个方法能够清除掉key ==null的实例,防止内存泄漏。
private Entry getEntry(ThreadLocal<?> key) { int i = key.threadLocalHashCode & (table.length - 1); Entry e = table[i]; if (e != null && e.get() == key) return e; else return getEntryAfterMiss(key, i, e); }
因为采用了开放定址法,当前keu的散列值和元素在数组中的索引并非一一对应的,首先取一个猜想数(key的散列值),若是所对应的key是咱们要找的元素,那么直接返回,不然调用getEntryAfterMiss
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) { Entry[] tab = table; int len = tab.length; while (e != null) { ThreadLocal<?> k = e.get(); if (k == key) return e; if (k == null) expungeStaleEntry(i); else i = nextIndex(i, len); e = tab[i]; } return null; }
这里一直在探测寻找下一个元素,知道找的元素的key是咱们要找的。这里当key==null时,调用expungeStaleEntry有利于GC的回收,用于防止内存泄漏。
ThreadLocalMap的key为ThreadLocal实例,他是一个弱引用,咱们知道弱引用有利于GC的回收,当key == null时,GC就会回收这部分空间,但value不必定能被回收,由于他和Current Thread之间还存在一个强引用的关系。
因为这个强引用的关系,会致使value没法回收,若是线程对象不消除这个强引用的关系,就可能会出现OOM。有些时候,咱们调用ThreadLocalMap的remove()方法进行显式处理。
ThreadLocal不是用来解决共享变量的问题,也不是协调线程同步,他是为了方便各线程管理本身的状态而引用的一个机制。
每一个ThreadLocal内部都有一个ThreadLocalMap,他保存的key是ThreadLocal的实例,他的值是当前线程的局部变量的副本的值。