ThreadLocal原理简介和内存泄漏

ThreadLocal

This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its {@code get} or {@code set} method) has its own, independently initialized copy of the variable. {@code 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)

这个类提供了线程本地变量。通过访问这些变量(通过get()或set()方法),都是访问线程的私有变量。ThreadLocal实例通常在类中声明为private static字段,目的是将状态与一个线程相关联

官方使用

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

ThreadLocal简单使用

public class TLDemo {
    private ThreadLocal<String> threadLocal1 = new ThreadLocal<>();
    private ThreadLocal<Integer> threadLocal2 = new ThreadLocal<>();
    
    public void testLocal() throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadLocal1.set("Thread 1");
                threadLocal2.set(111);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I am T1: " + threadLocal1.get());
                System.out.println("I am T1: " + threadLocal2.get());
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                threadLocal1.set("Thread 2");
                threadLocal2.set(222);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I am T2: " + threadLocal1.get());
                System.out.println("I am T2: " + threadLocal2.get());

            }
        });
        t1.start();
        t2.start();
    }
    
}

class Main{
    public static void main(String[] args) throws InterruptedException {
        TLDemo demo = new TLDemo();
        demo.testLocal();
        /*
        * I am T1: Thread 1
		* I am T1: 111
		* I am T2: Thread 2
		* I am T2: 222
        */
    }
}

可以看到ThreadLocal为每个线程都保存了对应的副本,使不同线程访问变量时能够访问自己的变量

ThreadLocal,Thread, ThreadLocalMap关系

ThreadLocalMapThreadLocal的静态内部类,ThreadLocal内部还有一个继承了WeakReferenceEntry内部类

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

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

ThreadLocalMap类的定义是在ThreadLocal类中,真正的引用在Thread类中,ThreadLocalMapThread的属性

Set和Get方法

ThreadLocalset()方法

    public void set(T value) {
        Thread t = Thread.currentThread(); // 获取当前线程
        ThreadLocalMap map = getMap(t); // 获取ThreadLocalMap  
        if (map != null) // map不为空 直接复制,key不是当前ThreadLocal,是ThreadLocal实例的一个弱引用WeakReference
            map.set(this, value);
        else
            createMap(t, value);
    }

getMap()方法,入参为线程,返回值为入参线程t的ThreadLocalMap的实例(属性)

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

createMap()方法

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

get()方法

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

小结

  1. Thread类中有一个成员变量属于ThreadLocalMap类(一个定义在ThreadLocal类中的内部类),ThreadLocal并没有实现Map接口,他的key是ThreadLocal实例的弱引用
  2. 当为ThreadLocal类的对象set值时,首先获得当前线程的ThreadLocalMap类属性,然后以ThreadLocal类的对象的弱引用key,设定value。get值时则类似。
  3. ThreadLocal变量的活动范围为某线程,是该线程“专有的,独自霸占”的,对该变量的所有操作均由该线程完成!
    ThreadLocal不是用来解决共享对象的多线程访问的竞争问题的,因为ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。
    当线程终止后,这些值会作为垃圾回收。
  4. ThreadLocal实例的value是Objectget()方法会对Objeact转型处理。
  5. 每个线程都有一个ThreadLocalMap属性

ThreadLocal对象区分问题

ThreadLocal源码

private final int threadLocalHashCode = nextHashCode();
private static AtomicInteger nextHashCode = new AtomicInteger();
private static final int HASH_INCREMENT = 0x61c88647;
private static int nextHashCode() {
      return nextHashCode.getAndAdd(HASH_INCREMENT);
}

final关键字保证了threadLocalHashCode在生成之后就不能被改变,
AtomicInteger 保证了多个同时实例化的ThreadLocal都能通过原子性操作获得独有的threadLocalHashCode属性,并且保持自增性
不使用Thread线程id作为ThreadLocal作为key的原因是无法区分ThreadLocalMap的多个value,例如ThreadLocalMap中的多个字符串,但ThreadLocal能够通过threadLocalHashCode的唯一性保证实例的唯一性

内存泄漏问题

ThreadLocalMap使用ThreadLocal的弱引用作为key,如图实线表示强引用,虚线表示弱引用
在这里插入图片描述
弱引用在系统GC时,一定会被回收

如果Entry的key是ThreadLocal实例的强引用,则即使删除ThreadLocal实例的强引用,因为Entry中key仍然保留着对ThreadLocal的强引用,JVM的GC无法回收ThreadLocal的实例,

如果Entry的key是ThreadLocal实例的弱引用,在删除了对ThreadLocal实例的强引用后,系统GC时,因为Entry中key对ThreadLocal是弱引用,该实例会被JVM的GC回收,key变为null,ThreadLocalMap也会清理key为null的Entry值,实现正确的回收
由上可知正确回收的前提是,手动清除ThreadLocal的强引用,因此在不需要ThreadLocal时,需要调用其remove()方法删除其强引用

如何删除key为null的Entry

ThreadLocalMap的getEntry函数的流程大概为:

首先从ThreadLocal的直接索引位置(通过ThreadLocal.threadLocalHashCode & (table.length-1)运算得到)获取Entry e,如果e不为null并且key相同则返回e;

如果e为null或者key不一致则向下一个位置查询,如果下一个位置的key和当前需要查询的key相等,则返回对应的Entry。否则,如果key值为null,则擦除该位置的Entry,并继续向下一个位置查询。

在这个过程中遇到的key为null的Entry都会被擦除,那么Entry内的value也就没有强引用链,自然会被回收。仔细研究代码可以发现,set操作也有类似的思想,将key为null的这些Entry都删除,防止内存泄露。

但是光这样还是不够的,上面的设计思路依赖一个前提条件:要调用ThreadLocalMap的getEntry函数或者set函数。这当然是不可能任何情况都成立的,所以很多情况下需要使用者手动调用ThreadLocal的remove函数,手动删除不再需要的ThreadLocal,防止内存泄露。
所以JDK建议将ThreadLocal变量定义成private static的,这样的话ThreadLocal的生命周期就更长,由于一直存在ThreadLocal的强引用,所以ThreadLocal也就不会被回收,也就能保证任何时候都能根据ThreadLocal的弱引用访问到Entry的value值,然后remove它,防止内存泄露。

1.使用ThreadLocal,建议用static修饰 static ThreadLocal headerLocal = new ThreadLocal();
2.使用完ThreadLocal后,执行remove操作,避免出现内存溢出情况。

关于ThreadLocalMap内部类的简单介绍
  初始容量16,负载因子2/3,解决冲突的方法是再hash法,也就是:在当前hash的基础上再自增一个常量。(开放寻址法?)

面试题参考
博客参考
博客参考
博客参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值