欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java开发中的ThreadLocal详解

程序员文章站 2022-06-21 13:53:30
ThreadLocal本质上,ThreadLocal通过空间来换取时间,从而实现每个线程当中都会有一个变量的副本,这样每个线程就会操作改副本,从而完全规避了多线程的并发问题。 public T get() { // 获取到当前线程对象 Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { Thread...

什么是ThreadLocal

本质上,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(); } public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } 

静态内部类

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

每个线程Thread都维护了自己的threadLocals变量,所以在每个线程创建ThreadLocal的时候,实际上数据是存在自己线程Thread的threadLocals变量里面的,别人没办法拿到,从而实现了隔离。

public class Thread implements Runnable { ... /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; ... } 

Java中存在四种类型的引用:

  1. 强引用(strong)
    垃圾回收不回收。
  2. 软引用(soft)
    在垃圾回收的时候,如果内存不够,则清理,否则不清理。
  3. 弱引用(weak)
    在下一次垃圾回收时,如果一个对象是弱引用,gc清理,对象被回收。
  4. 虚引用(phantom)

除了强引用用=new,其他三种都继承Reference:

public class WeakReference<T> extends Reference<T> {} 

ThreadLocal Entry为什么继承WeakReference

防止内存泄漏,如果Entry是强引用,Entry中的k永远无法得到释放,k,v越来越多。。。如果Entry是弱引用,在下一次垃圾回收的时候,弱引用ThreadLocal将会被回收。

static class Entry extends WeakReference<ThreadLocal<?>> {} 

ThreadLocal内存泄漏

内存泄漏的原因

Entry:k,v
Entry是弱引用,在下一次垃圾回收的时候,弱引用ThreadLocal将会被回收。Entry的k将指向null(k指向的ThreadLocal已经被回收),v将不能再被获取。造成内存泄漏。

怎么解决

ThreadLocal在set或者get方法的时候,程序会检查Entry数组,将k为null的Entry一一remove掉。

 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(); if (k == key) { e.value = value; return; } // 替换k为空的Entry if (k == null) { replaceStaleEntry(key, value, i); return; } } tab[i] = new Entry(key, value); int sz = ++size; if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); } 

在使用完ThreadLocal后执行remove方法

package com.learn.thread.local public class ThreadLocalTest { private static final ThreadLocal<String> name = new ThreadLocal(); public static void main(String[] args) { try { name.set("John"); System.out.println(checkUser()); } finally { name.remove(); } System.out.println(name.get()); } public static String checkUser() { if (name.get() == null) { return ""; } return name.get(); } } 

java开发中的ThreadLocal详解

本文地址:https://blog.csdn.net/wz122330/article/details/107666723

相关标签: 多线程