ThreadLocal原理分析

ThreadLocal是我们在工作中经常用来解决线程安全的一个类,那么,它到底是如何工作的呢?接下来让我们一起揭开它神秘的面纱。

如何使用

假如我们需要在service中,使用SimpleDateFormat对时间进行格式化

@Service
public class TestService {
    
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private StudentDao studentDao;


    public StudentVo getStudent(Long id) {
        Student student = studentDao.getStudent(id);
        StudentVo studentVo = new StudentVo();
        BeanUtils.copyProperties(student, studentVo);
        studentVo.setBirthday(simpleDateFormat.format(student.getBirthday()));
        System.out.println(studentVo);
        return studentVo;
    }
}

我们都知道SimpleDateFormat 不是线程安全的,这么使用就会存在线程安全问题,那么我们应该如何来解决这个问题呢?这个时候,ThreadLocal就上场了。

@Service
public class TestService {

    private ThreadLocal simpleDateFormatThreadLocal = new ThreadLocal() {

        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    @Autowired
    private StudentDao studentDao;


    public StudentVo getStudent(Long id) {
        Student student = studentDao.getStudent(id);
        StudentVo studentVo = new StudentVo();
        BeanUtils.copyProperties(student, studentVo);
        studentVo.setBirthday(simpleDateFormatThreadLocal.get().format(student.getBirthday()));
        System.out.println(studentVo);
        return studentVo;
    }
}

那么这究竟是什么原理呢

原理分析

ThreadLocal是通过线程隔离的形式实现线程安全的,他会为每个线程创建一个副本(每个线程都有一个独立的SimpleDateFormat对象),通过这种形式解决了线程安全问题,ThreadLocal

在每个线程中,都有一个ThreadLocalMap对象,这个也是一个hash map,它是采用数组+开放定址法来实现的。当我们向ThreadLocal中设置数据时,会降当前的ThreadLocal作为key,设置的数据作为value添加到hash map中

接下来,我们来分析一下具体的方法

set

public void set(T value) {
    // 获取当前的线程
    Thread t = Thread.currentThread();
    // 获取线程中的threadLocals属性
    ThreadLocalMap map = getMap(t);
    if (map != null)
        // 将value设置到threadLocals中
        map.set(this, value);
    else
        // 初始化threadLocals并设置值
        createMap(t, value);
}

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

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

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

        // threadLocal对象相同,覆盖value
        if (k == key) {
            e.value = value;
            return;
        }

        // k为null,表示这个弱引用的ThreadLocal对象因内存不足被回收了,因此,可以进行替换
        if (k == null) {
            // 
            replaceStaleEntry(key, value, i);
            return;
        }
    }
    // 找到了第一个空的数组节点,将元素放到此位置
    tab[i] = new Entry(key, value);
    int sz = ++size;
    // 清理被回收的ThreadLocal对象
    if (!cleanSomeSlots(i, sz) && sz >= threshold)
        // 扩容
        rehash();
}

// 开放定址法,计算下一个位置
private static int nextIndex(int i, int len) {
    return ((i + 1 < len) ? i + 1 : 0);
}

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

    Entry(ThreadLocal<?> k, Object v) {
        // key使用弱引用存储
        super(k);GC时会
        value = v;
    }
}


这段代码比较简单,首先会获取当前线程,然后从线程中获取threadLocals属性,如果未初始化,则初始化threadLocals 属性(通过构造函数设置初始化),如果已初始化,则通过set方法设置值(key未当前的ThreadLocal对象)

get

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        // 获取entry
        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;
}

private Entry getEntry(ThreadLocal<?> key) {
    // 计算key在数组中的位置
    int i = key.threadLocalHashCode & (table.length - 1);
    Entry e = table[i];
    // 当前位置的元素不为空,且key相等
    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();
        // key相等,找到了元素
        if (k == key)
            return e;
        if (k == null)
            expungeStaleEntry(i);
        else
            // 获取元素的下一个位置
            i = nextIndex(i, len);
        e = tab[i];
    }
    // key不存在,返回null
    return null;
}

Remove

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


private void remove(ThreadLocal<?> key) {
    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)]) {
        if (e.get() == key) {
            e.clear();
            expungeStaleEntry(i);
            return;
        }
    }
}

ThreadLocal为什么采用开放定址法来实现Map

  1. 对于ThreadLocal来说,存储的元素并不会很多,采用开放定址法更加节省内存

内存泄漏问题

我们常说ThreadLocal会产生内存泄漏问题,那么,究竟是什么原因造成的呢

通过上面的源码分析,我们知道,ThreadLocal会和线程绑定在一起,在线程没有回收的时候,ThreadLocal变量就不会被回收(key采用弱引用,在GC的时候会被回收,但是value不会被回收),因此,我们必须要记住,ThreadLocal在使用完之后,必须调用remove方法清理内存(ThreadLocal自带的清理方法必须要在调用方法的情况下,才会清理掉key为空的entry)

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章