Java多线程之ThreadLocal原理

       首先看下面这个demo,如果多个线程共享一个实例对象,并修改和访问对象内部数据,看看执行会有什么结果。

public class ThreadLocalTest {
    static class AddClass {
        private Integer value = 0;

        void add() {
            value++;
        }

        Integer getValue() {
            return value;
        }
    }

    private static void sleep() {
        try {
            Thread.sleep((int) (Math.random() * 100 + 1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final AddClass addClass = new AddClass();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < 4; j++) {
                    addClass.add();
                    System.out.println(Thread.currentThread().getName() + ":" + addClass.getValue());
                    sleep();
                }
            }).start();
        }
    }
}

  sleep方法主要是为了模拟真实多线程环境,让效果更佳明显。

执行后结果为

Thread-1:1
Thread-0:2
Thread-2:3
Thread-0:4
Thread-2:5
Thread-2:6
Thread-1:7
Thread-0:8
Thread-0:9
Thread-1:10
Thread-2:11
Thread-1:12

可以看到addClass对象的value在交错执行的线程中递增,可以说此时AddClass是线程不安全的。

如果利用线程同步机制,对addClass对象加锁呢?

    public static void main(String[] args) {
        final AddClass addClass = new AddClass();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                synchronized (addClass) {
                    for (int j = 0; j < 4; j++) {
                        addClass.add();
                        System.out.println(Thread.currentThread().getName() + ":" + addClass.getValue());
                        sleep();
                    }
                }
            }).start();
        }
    }

执行后结果是

Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-2:5
Thread-2:6
Thread-2:7
Thread-2:8
Thread-1:9
Thread-1:10
Thread-1:11
Thread-1:12

各个线程按先后顺序完成了对addClass对象的操作,没有发生交替。

但是,此时我们有了新的需求,我们要求各个线程对addClass对象的访问结果彼此不受影响,也就是每个线程都想对有初始值的addClass对象进行操作,该怎么做呢?

每个线程new一个AddClass操作?抱歉,只给你一个AddClass实例。

在实际开发中,像Session对象,数据库连接对象等都用到了ThreadLocal,达到了多线程访问互不干扰的目的。

这时,主角ThreadLocal登场了!

public class ThreadLocalTest {
    static class AddClass {
        private ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
            public Integer initialValue() {
                return 0;
            }
        };

        void add() {
            value.set(value.get() + 1);
        }

        Integer getValue() {
            return value.get();
        }
    }

    private static void sleep() {
        try {
            Thread.sleep((int) (Math.random() * 100 + 1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final AddClass addClass = new AddClass();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < 4; j++) {
                    addClass.add();
                    System.out.println(Thread.currentThread().getName() + ":" + addClass.getValue());
                    sleep();
                }
            }).start();
        }
    }
}

执行结果如下

Thread-1:1
Thread-0:1
Thread-2:1
Thread-2:2
Thread-2:3
Thread-1:2
Thread-2:4
Thread-0:2
Thread-1:3
Thread-0:3
Thread-1:4
Thread-0:4

此处实例化ThreadLocal对象时,覆盖了ThreadLocal的initialValue方法,这个方法是一个延时方法,不会立即执行,会在第一次调用get方法时执行一次。

就好像每个线程都有一个单独的addClass对象一样,彼此间完全没有关联影响。

与同步机制相比,同步机制采用了“以时间换空间”的方式:访问串行化,对象共享化。而ThreadLocal采用了“以空间换时间”的方式:访问并行化,对象独享化。

ThreadLocal使用了什么魔法办到的呢?如果让你去实现ThreadLocal,你会怎么做呢?大多数人肯定想到了Map,是的,ThreadLocal内部定义了一个Map,先看一下ThreadLocal内部几个重要的方法。

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

    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

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

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

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

我们刚刚提到的那个map在ThreadLocal中就是ThreadLocalMap。

在第一次调用ThreadLocal的get或set方法时,会创建ThreadLocalMap。

我们发现ThreadLocal把ThreadLocalMap对象交给了Thread的threadLocals变量,这个变量又是个什么东东?查看一下Thread的源码,如下

    class Thread implements Runnable {
        //省略...
        ThreadLocal.ThreadLocalMap threadLocals = null;
        //省略...
    }

原来ThreadLocal里面仅仅是定义了ThreadLocalMap,通过createMap方法在每个线程第一次调用ThreadLocal的get或set方法时,创建ThreadLocalMap对象,并把ThreadLocalMap对象交给了对应访问线程Thread保管。ThreadLocal中的get、set方法中访问ThreadLocalMap对象时,调用getMap方法,传入当前操作的线程Thread,获取到对应线程保管的ThreadLocalMap,从而访问到对应线程保管的独享数据。我们谈到ThreadLocal经常讲到每个线程复制一份数据,就是这里所讲的使用createMap,为每个线程创建了一个ThreadLocalMap对象,并交由Thread自身保管,ThreadLocalMap中包含了这份数据。

下面摘取了一部分ThreadLocalMap的源码。

    static class ThreadLocalMap {
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /**
             * The value associated with this ThreadLocal.
             */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

        private static final int INITIAL_CAPACITY = 16;

        private Entry[] table;

        private int threshold;

        private void setThreshold(int len) {
            threshold = len * 2 / 3;
        }

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

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

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

        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }
    }

ThreadLocalMap中包含了一个初始大小为16的Entry数组table。threshold被设置成现有容量的2/3,它表示保存数据数量超过现有容量的2/3时,需要扩容。

在ThreadLocal的get方法里面可以看到,使用了 ThreadLocalMap.Entry e = map.getEntry(this)来获取要操作的数据,this就是ThreadLocal对象。查看getEntry方法会发现table数组索引计算方式为:int i = key.threadLocalHashCode & (table.length - 1);

可以看出ThreadLocalMap与我们常说的HashMap不同,它自己实现了存取数据的操作方式。当有多个ThreadLocal对象时,以ThreadLocal对象参与索引计算得出索引,找到对应ThreadLocal保存的数据。

public class ThreadLocalTest {
    static class AddClass {
        private ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
            public Integer initialValue() {
                return 0;
            }
        };

        private ThreadLocal<Integer> value2 = new ThreadLocal<Integer>() {
            public Integer initialValue() {
                return 100;
            }
        };

        void add() {
            value.set(value.get() + 1);
            value2.set(value2.get() + 1);
        }

        Integer getValue() {
            return value.get();
        }

        Integer getValue2() {
            return value2.get();
        }
    }

    private static void sleep() {
        try {
            Thread.sleep((int) (Math.random() * 100 + 1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final AddClass addClass = new AddClass();
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                for (int j = 0; j < 4; j++) {
                    addClass.add();
                    System.out.println(Thread.currentThread().getName() + ":value=" + addClass.getValue() + "&value2=" + addClass.getValue2());
                    sleep();
                }
            }).start();
        }
    }
}

输出为:

Thread-0:value=1&value2=101
Thread-1:value=1&value2=101
Thread-2:value=1&value2=101
Thread-1:value=2&value2=102
Thread-1:value=3&value2=103
Thread-2:value=2&value2=102
Thread-0:value=2&value2=102
Thread-1:value=4&value2=104
Thread-2:value=3&value2=103
Thread-0:value=3&value2=103
Thread-2:value=4&value2=104
Thread-0:value=4&value2=104

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值