ThreadLocal存储原理

首先每一个Thread都有一个ThreadLocal.Values类型的localValues变量,ThreadLocal的set,get方法如下:

public void set(T value) {
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values == null) {
            values = initializeValues(currentThread);
        }
        values.put(this, value);
    }

public T get() {
        // Optimized for the fast path.
        Thread currentThread = Thread.currentThread();
        Values values = values(currentThread);
        if (values != null) {
            Object[] table = values.table;
            int index = hash & values.mask;
            if (this.reference == table[index]) {
                return (T) table[index + 1];
            }
        } else {
            values = initializeValues(currentThread);
        }

        return (T) values.getAfterMiss(this);
    }
values方法如下
Values values(Thread current) {
        return current.localValues;
    }
可以看到不管是set还是get 首先都会调用values(currentThread)来获取local'Values进行存取。localValues是每个线程的局部变量,所以就实现了线程本地存储。至于set和get的具体实现可以阅读源码。


你可能感兴趣的:(ThreadLocal存储原理)