ThreadLocal和InheritableThreadLocal源码学习(一)

最近在熟悉公司业务代码的时候发现有使用了ThreadLocal去控制线程变量的部分,特此学习一下

ThreadLocal

ThreadLocal提供了线程内存储变量的能力,这些变量不同之处在于每一个线程读取的变量是对应的互相独立的。通过get和set方法就可以得到当前线程对应的值。

创建ThreadLocal:这里实例化的是InheritableThreadLocal,
因为这样父线程生成的变量就可以传递到子线程中进行使用(看业务需求使用)

private static final ThreadLocal<CommonInvocationInfo> threadLocal = new InheritableThreadLocal<>();


ThreadLocal的set方法

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

createMap():

void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

map.set()调用的是ThreadLocalMap中的set():

private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

看一下其构造方法,其实ThreadLocalMap就是一个Entry数组,封装着线程所需存储的变量

		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);
		}

这里的Entry是ThreadLocalMap的一个静态内部类,弱引用特性

	static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }
        
        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;

        ...


get方法:可以发现ThreadLocal是根据 ThreadLocalMap(这里其实是一个静态内部类) 维护的

	public T get() {
        Thread t = Thread.currentThread();
        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();
    }

getMap():从当前Thread获取threadlocal

/**
     * 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;
    }

同样这里getEntry()调用的是ThreadLocalMap中的

 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);
        }



InheritableThreadLocal

暂无



先简单实现一个由ThreadLocal管理的类

public class StudentThreadLocal {

    public static final ThreadLocal<Student> studentLocal = new InheritableThreadLocal<Student>();

    public void  init() {
        if(studentLocal.get()!=null) {
            return;
        }else {
            studentLocal.set(new Student());
        }
    }

    public void setName(String name) {
        studentLocal.get().setName(name);
    }

    public String getName() {
        return studentLocal.get().getName();
    } 
}

测试

public static void main(String[] args) throws InterruptedException {
        StudentThreadLocal studentThreadLocal = new StudentThreadLocal();
        studentThreadLocal.init();
        studentThreadLocal.setName("马化腾");
        System.out.println(studentThreadLocal.getName());
        Thread thread=new Thread(new Runnable() {
            public void run() {
                StudentThreadLocal studentThreadLocal = new StudentThreadLocal();
                studentThreadLocal.init();
                studentThreadLocal.setName("马匹");
            }
        });
        thread.start();
        Thread.sleep(200);
        System.out.println(studentThreadLocal.getName());
    }

输出结果:

马化腾
马匹

可以发现都是同一个ThreadLocal,因为使用的是InheritableThreadLocal

同样,换一个线程测试一下,先让下面的方法先运行,在运行上一个

    public static void main(String[] args) throws InterruptedException {
        StudentThreadLocal studentThreadLocal=new StudentThreadLocal();
        studentThreadLocal.init();
        studentThreadLocal.setName("sdasadsa");
        Thread.sleep(5000);
        System.out.println(studentThreadLocal.getName());

    }

输出结果:

马化腾
马匹

发现每个线程都有自己独立管理的ThreadLocal

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值