ThreadLocal

一:使用

public class UseThreadLocal {
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    private static ThreadLocal<Integer> threadLocal2 = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 100;
        }
    };

    /**
     * 运行3个线程
     */
    public void startThreadArray() {
        Thread[] runs = new Thread[3];
        for (int i = 0; i < runs.length; i++) {
            runs[i] = new Thread(new TestRunnable(i));
        }
        for (int i = 0; i < runs.length; i++) {
            runs[i].start();
        }
    }

    /**
     * 测试线程,线程的工作是将ThreadLocal变量的值变化,并写回,看看线程之间是否会互相影响
     */
    public static class TestRunnable implements Runnable {
        int id;

        public TestRunnable(int id) {
            this.id = id;
        }

        public void run() {
            Integer initialValue = threadLocal.get();
            initialValue = initialValue + id;
            threadLocal.set(initialValue);
            System.out.println(Thread.currentThread().getName()
                    + ":" + threadLocal.get());
            threadLocal.remove();

            Integer initialValue2 = threadLocal2.get();
            initialValue2 = initialValue2 + id;
            threadLocal2.set(initialValue2);
            System.out.println(Thread.currentThread().getName()
                    + ":" + threadLocal2.get());
            threadLocal2.remove();
        }
    }

    public static void main(String[] args) {
        UseThreadLocal test = new UseThreadLocal();
        test.startThreadArray();
    }
}

二:源码分析

get方法

TheadLcoal对象有值的话获取并设置,没有的话创建

  public T get() {
        //当前线程作为key,获取线程独有的Trheadlocalmap
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            //当前threadload作为键,获取真正存储的值
            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;
    }

ThreadLocalMap

从上get源码分析得知TheadLocal对象用把当前线程作为key,获取每个线程独有的ThreadLocalMap。
ThreadLocalMap使用当前ThreadLocal对象作为key,获取每个线程的值。
通过这样的机制,多个线程使用同一个TheadLocal对象,TheadLocal对象在每个线程里面获取的值都是该线程独有的值,从而达到线程隔离的目的。

 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;
            }
        }
        
        ...
          private Entry[] table;

ThreadLocalMap 存放着Entry数组,意味着一个线程可以存放多个变量。

整体结构

在这里插入图片描述

三:ThreadLocal可能引发的内存泄露

key因为是弱引用,gc发生的时候可以被回收,但是由于map里面的value是强引用,所以不进行clear的话,可能会发生泄露。

 public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XATEmiwn-1653894117651)(evernotecid://0777E4E5-DD5E-4B9E-BAB2-FB2751D0CA6C/appyinxiangcom/22543568/ENResource/p810)]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林树杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值