ThreadLocal浅析
jopen
9年前
前言
在《Spring 3.x 企业应用开发实战》中我看到ThreadLocal这个类,当时自己错误的认为这个类可以解决并发,还自己总结 编发中的锁是“时间换空间”,ThreadLocal类是“空间换时间”,当我看了ThreadLocal的源码后才发现 自己的理解完全错了。其实ThreadLocal不是用于解决共享变量的问题的,不是为了协调线程同步而存在,而是为了方便每个线程处理自己的状态而引入的一个机制。
官方对THreadLocal的描述
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID). 从中可以总结出三点: (1)每个线程都有自己的局部变量 (2)独立于变量的初始化副本 (3)状态与某一个线程相关联
例子来理解ThreadLocal
//例1 public class ThreadLocalTest { //创建一个Integer型的线程本地变量 public static final ThreadLocal<Integer> local = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return 0; } }; public static void main(String[] args) throws InterruptedException { Thread[] threads = new Thread[5]; for (int j = 0; j < 5; j++) { threads[j] = new Thread(new Runnable() { public void run() { //获取当前线程的本地变量,然后累加5次 int num = local.get(); for (int i = 0; i < 5; i++) { num++; } //重新设置累加后的本地变量 local.set(num); System.out.println(Thread.currentThread().getName() + " : " + local.get()); } }, "Thread-" + j); } for (Thread thread : threads) { thread.start(); } } } //执行结果 Thread-0 : 5 Thread-1 : 5 Thread-2 : 5 Thread-3 : 5 Thread-4 : 5
//例2 public class ThreadLocalTest { private static Index num = new Index(); //创建一个Index类型的本地变量 private static ThreadLocal<Index> local = new ThreadLocal<Index>() { @Override protected Index initialValue() { return num; } }; public static void main(String[] args) throws InterruptedException { Thread[] threads = new Thread[5]; for (int j = 0; j < 5; j++) { threads[j] = new Thread(new Runnable() { public void run() { //取出当前线程的本地变量,并累加10000次 Index index = local.get(); for (int i = 0; i < 10000; i++) { index.increase(); } System.out.println(Thread.currentThread().getName() + " : "+ index.num); } }, "Thread-" + j); } for (Thread thread : threads) { thread.start(); } } static class Index { int num; public void increase() { num++; } } } //执行结果 Thread-0 : 11611 Thread-1 : 11613 Thread-2 : 22393 Thread-3 : 30219 Thread-4 : 40219
为什么两例子会出现不同结果,根据代码我们可以看出例1复制的是对象,例2复制的是对象的引用。
jdk老版本ThreadLocal的实现
《Spring 3.x 企业应用开发实战》中对ThreadLocal的简单实现,其实这个是jdk以前实现的思路,但是存在性能问题,现在已经不这样实现,大家了解下。实现的思路很简单:在ThreadLocal类中有一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值对应线程的变量副本。
public class SimpleThreadLocal { private Map valueMap = Collections.synchronizedMap(new HashMap()); public void set(Object newValue) { //①键为线程对象,值为本线程的变量副本 valueMap.put(Thread.currentThread(), newValue); } public Object get() { Thread currentThread = Thread.currentThread(); //②返回本线程对应的变量 Object o = valueMap.get(currentThread); //③如果在Map中不存在,放到Map中保存起来 if (o == null && !valueMap.containsKey(currentThread)) { o = initialValue(); valueMap.put(currentThread, o); } return o; } public void remove() { valueMap.remove(Thread.currentThread()); } public Object initialValue() { return null; } }
jdk1.7ThreadLocal的实现
源码缝隙思路:ThreadLocal中set值,然后get取出值
set值
set()方法
public void set(T value) { //获取当前线程 Thread t = Thread.currentThread(); //获取ThreadLocalMap ThreadLocalMap map = getMap(t); if (map != null) //map存在在set(key,value),注意key是this,代表当前ThreadLocal实例 map.set(this, value); else //不存在则创建,t是当前线程 createMap(t, value); }
createMap()方法
//ThreadLocalMap是ThreadLocal内部类 void createMap(Thread t, T firstValue) { //每个线程都有一个ThreadLocalMap t.threadLocals = new ThreadLocalMap(this, firstValue); }
ThreadLocalMap类
//构造方法 //设置map的key值为threadLocal对象,value为参数中的object。 ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) { table = new Entry[INITIAL_CAPACITY]; int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); table[i] = new Entry(firstKey, firstValue); size = 1; setThreshold(INITIAL_CAPACITY); }
//对ThreadLocal软引用 static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }
get值
get()方法
public T get() { Thread t = Thread.currentThread(); //获得ThreadLocalMap ThreadLocalMap map = getMap(t); if (map != null) { //存在则获取值 ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } //不存在则初始化值 return setInitialValue(); }
//初始化值 private T setInitialValue() { //初始化为null T value = initialValue(); Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) //set值 map.set(this, value); else //map不存在则创建 createMap(t, value); return value; }
走读源码总结:
ThreadLocal