ThreadLocal浅析


前言

在《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复制的是对象的引用。java

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取出值ide

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()方法this

//ThreadLocalMap是ThreadLocal内部类
void createMap(Thread t, T firstValue) {
    //每一个线程都有一个ThreadLocalMap
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

ThreadLocalMap类
spa

//构造方法
//设置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;
}

走读源码总结:code

       ThreadLocal类中有个内部类ThreadLocalMap,这个Map的key值是threadlocal实例,因此说ThreadLocal为线程局部变量。orm

相关文章
相关标签/搜索