ThreadLocal 表面上看他是和多线程,线程同步有关的一个工具类,但其实他与线程同步机制无关。线程同步机制是多个线程共享同一个变量,而ThreadLocal是为每个线程创建一个单独的变量副本,每个线程都可以改变自己的变量副本而不影响其它线程所对应的副本。
ThreadLocal翻译成中文比较准确的叫法应该是:线程局部变量。
ThreadLocal定义了四个方法:
如果ThreadLocal.set()进去的东西本来就是多个线程共享的同一个对象,那么多个线程的ThreadLocal.get()取得的还是这个共享对象本身,还是有并发访问问题。
下面来看一个hibernate中典型的ThreadLocal的应用:
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; }
可以看到在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怎么来实现呢?可能就要在action中创建session,然后把session一个个传到service和dao中,这可够麻烦的。或者可以自己定义一个静态的map,将当前thread作为key,创建的session作为值,put到map中,应该也行,这也是一般人的想法,但事实上,ThreadLocal的实现刚好相反,它是在每个线程中有一个map,而将ThreadLocal实例作为key,这样每个map中的项数很少,而且当线程销毁时相应的东西也一起销毁了,不知道除了这些还有什么其他的好处。
总之,ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。归纳了两点:
1。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。
2。将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
当然如果要把本来线程共享的对象通过ThreadLocal.set()放到线程中也可以,可以实现避免参数传递的访问方式,但是要注意get()到的是那同一个共享对象,并发访问问题要靠其他手段来解决。但一般来说线程共享的对象通过设置为某类的静态变量就可以实现方便的访问了,似乎没必要放到线程中。
ThreadLocal的应用场合,我觉得最适合的是按线程多实例(每个线程对应一个实例)的对象的访问,并且这个对象很多地方都要用到。
类SimpleDateFormat 主要负责日期的转换与格式化,但在多线程的环境中,使用此类容易造成数据转换及处理的不准确,因为 SimpleDateFormat 类并不是线程安全的。
那么将SimpleDateFormat作为每个线程的局部变量的副本就是每个线程都拥有自己的SimpleDateFormat,就不存在线程安全问题了。
例子1,出现异常
package com.newwork.tandashi; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author tandashi * SimpleDateFormat 多线程下有线程安全问题 * */ public class MyThread extends Thread{ private SimpleDateFormat sdf; private String dateString; public MyThread(SimpleDateFormat sdf,String dateString){ this.sdf = sdf; this.dateString = dateString; } @Override public void run() { try { Date newDate = sdf.parse(dateString); String newDateString = sdf.format(newDate); if(!newDateString.equals(dateString)){ System.out.println(this.getName()+"的日期:"+dateString +"转化日期后出错:"+newDateString); } } catch (ParseException e) { e.printStackTrace(); } } }
运行测试类
package com.newwork.tandashi; import java.text.SimpleDateFormat; /** * * @author tandashi * SimpleDateFormat 多线程下有线程安全问题,测试类 * 转换出错 * */ public class ThredTest { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String[] dateString = new String[]{"2000-01-01","2000-01-02","2000-01-03","2010-10-01"}; MyThread[] threads = new MyThread[4]; for (int i = 0; i < threads.length; i++) { threads[i] = new MyThread(sdf,dateString[i]); } for (int i = 0; i < threads.length; i++) { threads[i].start(); } } }
运行结果
Thread-3的日期:2010-10-01转化日期后出错:1999-11-03 Thread-0的日期:2000-01-01转化日期后出错:1999-12-31 Thread-1的日期:2000-01-02转化日期后出错:1999-11-03 Thread-2的日期:2000-01-03转化日期后出错:1999-11-03
解决异常方法
package com.newwork.tandashi; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author tandashi * 使用ThreadLocal 存放 SimpleDateFormat */ public class MyThreadTwo extends Thread{ private SimpleDateFormat sdf; private String dateString; public MyThreadTwo(SimpleDateFormat sdf,String dateString){ this.sdf = sdf; this.dateString = dateString; } @Override public void run() { try { SimpleDateFormat sdf = DateTools.getSimpleDateFormat("yyyy-MM-dd"); Date newDate = sdf.parse(dateString); String newDateString = sdf.format(newDate).toString(); if(!newDateString.equals(dateString)){ System.out.println(this.getName() +"的日期:"+dateString +"转换后出错:"+newDateString); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
类 DateTools.java
package com.newwork.tandashi; import java.text.SimpleDateFormat; public class DateTools { private static ThreadLocal<SimpleDateFormat> t1 = new ThreadLocal<SimpleDateFormat>(); public static SimpleDateFormat getSimpleDateFormat(String pattern){ SimpleDateFormat sdf = null; sdf = t1.get(); if(sdf == null){ sdf = new SimpleDateFormat(pattern); t1.set(sdf); } return sdf; } }
运行测试类
package com.newwork.tandashi; import java.text.SimpleDateFormat; public class ThredTest2 { public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String[] dateString = new String[]{"2000-01-01","2000-01-02","2000-01-03","2010-10-01"}; MyThreadTwo[] thread = new MyThreadTwo[4]; for (int i = 0; i < thread.length; i++) { thread[i] = new MyThreadTwo(sdf,dateString[i]); } for (int i = 0; i < thread.length; i++) { thread[i].start(); } } }
运行后无结果输出。
例子2
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())); } } }
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 { ...... } }
可以看到ThreadLocal类中的变量只有这3个int型:
private final int threadLocalHashCode = nextHashCode(); private static int nextHashCode = 0; private static final int HASH_INCREMENT = 0x61c88647;
而作为ThreadLocal实例的变量只有 threadLocalHashCode 这一个,nextHashCode 和HASH_INCREMENT 是ThreadLocal类的静态变量,实际上HASH_INCREMENT是一个常量,表示了连续分配的两个ThreadLocal实例的threadLocalHashCode值的增量,而nextHashCode 的表示了即将分配的下一个ThreadLocal实例的threadLocalHashCode 的值。
可以来看一下创建一个ThreadLocal实例即new ThreadLocal()时做了哪些操作,从上面看到构造函数ThreadLocal()里什么操作都没有,唯一的操作是这句:
private final int threadLocalHashCode = nextHashCode();
那么nextHashCode()做了什么呢:
private static synchronized int nextHashCode() { int h = nextHashCode; nextHashCode = h + HASH_INCREMENT; return h; }
就是将ThreadLocal类的下一个hashCode值即nextHashCode的值赋给实例的threadLocalHashCode,然后nextHashCode的值增加HASH_INCREMENT这个值。
因此ThreadLocal实例的变量只有这个threadLocalHashCode,而且是final的,用来区分不同的ThreadLocal实例,ThreadLocal类主要是作为工具类来使用,那么ThreadLocal.set()进去的对象是放在哪儿的呢?
看一下上面的set()方法,两句合并一下成为
ThreadLocalMap map = Thread.currentThread().threadLocals;
这个ThreadLocalMap 类是ThreadLocal中定义的内部类,但是它的实例却用在Thread类中:
public class Thread implements Runnable { ...... /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; ...... }
这句
if (map != null) map.set(this, value);
也就是将该ThreadLocal实例作为key,要保持的对象作为值,设置到当前线程的ThreadLocalMap 中,get()方法同样大家看了代码也就明白了。
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()方法进行显式处理。
原文:https://www.cnblogs.com/mindOpen/p/11489139.html