栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java ThreadLocal用法实例详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java ThreadLocal用法实例详解

本文实例讲述了Java ThreadLocal用法。分享给大家供大家参考,具体如下:

目录
  • ThreadLocal的基本使用
  • ThreadLocal实现原理
  • 源码分析(基于openjdk11)
    • get方法:
      • setInitialValue方法
      • getEntry方法
    • set方法
      • ThreadLocalMap的set方法
        • replaceStaleEntry方法
        • cleanSomeSlots方法
        • rehash方法
        • expungeStaleEntries方法
        • resize方法

ThreadLocal实现了Java中线程局部变量。所谓线程局部变量就是保存在每个线程中独有的一些数据,我们知道一个进程中的所有线程是共享该进程的资源的,线程对进程中的资源进行修改会反应到该进程中的其他线程上,如果我们希望一个线程对资源的修改不会影响到其他线程,那么就需要将该资源设为线程局部变量的形式。

ThreadLocal的基本使用

如下示例所示,定义两个ThreadLocal变量,然后分别在主线程和子线程中对线程局部变量进行修改,然后分别获取线程局部变量的值:

public class ThreadLocalTest {

  private static ThreadLocal threadLocal1 = ThreadLocal.withInitial(() -> "threadLocal1 first value");
  private static ThreadLocal threadLocal2 = ThreadLocal.withInitial(() -> "threadLocal2 first value");

  public static void main(String[] args) throws Exception{


    Thread thread = new Thread(() -> {

      System.out.println("================" + Thread.currentThread().getName() + " enter=================");

      // 子线程中打印出初始值
      printThreadLocalInfo();

      // 子线程中设置新值
      threadLocal1.set("new thread threadLocal1 value");
      threadLocal2.set("new thread threadLocal2 value");

      // 子线程打印出新值
      printThreadLocalInfo();

      System.out.println("================" + Thread.currentThread().getName() + " exit=================");
    });

    thread.start();
    // 等待新线程执行
    thread.join();
    
    // 在main线程打印threadLocal1和threadLocal2,验证子线程对这两个变量的修改是否会影响到main线程中的这两个值
    printThreadLocalInfo();
    // 在main线程中给threadLocal1和threadLocal2设置新值
    threadLocal1.set("main threadLocal1 value");
    threadLocal2.set("main threadLocal2 value");
    // 验证main线程中这两个变量是否为新值
    printThreadLocalInfo();
  }

  private static void printThreadLocalInfo() {
    System.out.println(Thread.currentThread().getName() + ": " + threadLocal1.get());
    System.out.println(Thread.currentThread().getName() + ": " + threadLocal2.get());
  }
}

运行结果如下:

================Thread-0 enter=================
Thread-0: threadLocal1 first value
Thread-0: threadLocal2 first value
Thread-0: new thread threadLocal1 value
Thread-0: new thread threadLocal2 value
================Thread-0 exit=================
main: threadLocal1 first value
main: threadLocal2 first value
main: main threadLocal1 value
main: main threadLocal2 value

如果子线程对threadLocal1和threadLocal2的修改会影响到main线程中的threadLocal1和threadLocal2,那么在main线程第一次printThreadLocalInfo();打印出的应该是修改后的新值,即为new thread threadLocal1 value和new thread threadLocal2 value和,但实际打印结果并不是这样,说明在新线程中对threadLocal1和threadLocal2的修改并不会影响到main线程中的这两个变量,似乎main线程中的threadLocal1和threadLocal2作用域仅局限于main线程,新线程中的threadLocal1和threadLocal2作用域仅局限于新线程,这就是线程局部变量的由来。

ThreadLocal实现原理

如下图所示

每个线程对象里会持有一个java.lang.ThreadLocal.ThreadLocalMap类型的threadLocals成员变量,而ThreadLocalMap里有一个java.lang.ThreadLocal.ThreadLocalMap.Entry[]类型的table成员,这是一个数组,数组元素是Entry类型,Entry中相当于有一个key和value,key指向所有线程共享的java.lang.ThreadLocal对象,value指向各线程私有的变量,这样保证了线程局部变量的隔离性,每个线程只是读取和修改自己所持有的那个value对象,相互之间没有影响。

源码分析(基于openjdk11)

源码包括ThreadLocal和ThreadLocalMap,ThreadLocalMap是ThreadLocal内定义的一个静态内部类,用于存储实际的数据。当调用ThreadLocal的get或者set方法时都有可能创建当前线程的threadLocals成员(ThreadLocalMap类型)。

get方法:

ThreadLocal的get方法定义如下

  
  public T get() {
  	// 获取当前线程
    Thread t = Thread.currentThread();
    // 获取当前线程的threadLocals成员变量,这是一个ThreadLocalMap
    ThreadLocalMap map = getMap(t);
    // threadLocals不为null则直接从threadLocals中取出ThreadLocal
    // 对象对应的值
    if (map != null) {
    	// 从map中获取当前ThreadLocal对象对应Entry对象
      ThreadLocalMap.Entry e = map.getEntry(this);
      if (e != null) {
      	// 获取ThreadLocal对象对应的value值
 @SuppressWarnings("unchecked")
 T result = (T)e.value;
 return result;
      }
    }
    // threadLocals为null,则需要创建ThreadLocalMap对象并赋给
    // threadLocals,将当前ThreadLocal对象作为key,调用initialValue
    // 获得的初始值作为value,放置到threadLocals的entry中;
    // 或者threadLocals不为null,但在threadLocals中未
    // 找到当前ThreadLocal对象对应的entry,则需要向threadLocals添加新的
    // entry,该entry以当前的ThreadLocal对象作为key,调用initialValue
    // 获得的值作为value
    return setInitialValue();
  }
  
  ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
  }

当Thread的threadLocals为null,或者在Thread的threadLocals中未找到当前ThreadLocal对象对应的entry,则进入到setInitialValue方法;否则进入到ThreadLocalMap的getEntry方法。

setInitialValue方法

定义如下:

  private T setInitialValue() {
  	// 获取初始值,如果我们在定义ThreadLocal对象时实现了ThreadLocal
  	// 的initialValue方法,就会调用我们自定义的方法来获取初始值,否则
  	// 使用initialValue的默认实现返回null值
    T value = initialValue();
    Thread t = Thread.currentThread();
    // 获取当前线程的threadLocals成员
    ThreadLocalMap map = getMap(t);
    if (map != null) {
    	// 若threadLocals存在则将ThreadLocal对象对应的value设置为初始值
      map.set(this, value);
    } else {
    	// 否则创建threadLocals对象并设置初始值
      createMap(t, value);
    }
    if (this instanceof TerminatingThreadLocal) {
      TerminatingThreadLocal.register((TerminatingThreadLocal) this);
    }
    return value;
  }

createMap方法实现

  
  void createMap(Thread t, T firstValue) {
  	// 创建一个ThreadLocalMap对象,用当前ThreadLocal对象和初始值value来
  	// 构造ThreadLocalMap中table的第一个entry。ThreadLocalMap对象赋
  	// 给线程的threadLocals成员
    t.threadLocals = new ThreadLocalMap(this, firstValue);
  }

ThreadLocalMap的构造方法定义如下:

    
    ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
    	// 构造table数组,数组大小为INITIAL_CAPACITY
      table = new Entry[INITIAL_CAPACITY];
      // 计算key(ThreadLocal对象)在table中的索引
      int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
      // 用ThreadLocal对象和value来构造entry对象,并放到table的第i个位置
      table[i] = new Entry(firstKey, firstValue);
      size = 1;
      // 设置table的阈值,当table中元素个数超过该阈值时需要对table
      // 进行resize,通常在调用ThreadLocalMap的set方法时会发生resize
      setThreshold(INITIAL_CAPACITY);
    }
    
    private void setThreshold(int len) {
      threshold = len * 2 / 3;
    }

这里firstKey.threadLocalHashCode是ThreadLocal中定义的一个hashcode,使用该hashcode进行hash运算从而找到该ThreadLocal对象对应的entry在table中的索引。

getEntry方法

定义如下:

    
    private Entry getEntry(ThreadLocal key) {
    	// 根据ThreadLocal的hashcode计算该ThreadLocal对象在table中的位置
      int i = key.threadLocalHashCode & (table.length - 1);
      Entry e = table[i];
      // e为null则table不存在key对应的entry;
      // e.get() != key 可能是由于hash冲突导致key对应的entry在table
      // 的另外一个位置,需要继续查找
      if (e != null && e.get() == key)
 return e;
      else
      	// e==null或者e.get() != key 继续查找key对应的entry
 return getEntryAfterMiss(key, i, e);
    }

getEntryAfterMiss方法定义如下:

    
    private Entry getEntryAfterMiss(ThreadLocal key, int i, Entry e){
      Entry[] tab = table;
      int len = tab.length;
			
			// 从table的第i个位置一直往后找,直到找到键为key的entry为止
      while (e != null) {
 ThreadLocal k = e.get();
 // 若k==key,则找到了entry
 if (k == key)
   return e;
 // k == null 需要删除该entry
 if (k == null)
   expungeStaleEntry(i);
 // k != key && k != null 继续往后寻找,nextIndex就是取(i+1)
 // 即table中第(i+1)个位置的entry
 else
   i = nextIndex(i, len);
 e = tab[i];
      }
      return null;
    }

expungeStaleEntry方法删除key为null的entry,删除后对staleSlot位置的entry和其后第一个为null的entry之间的entry进行一个rehash操作,rehash的目的是降低table发生碰撞的概率:

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

      // expunge entry at staleSlot
      // 删除staleSlot位置的entry
      tab[staleSlot].value = null;
      tab[staleSlot] = null;
      // table中元素个数减一
      size--;

      // Rehash until we encounter null
      // 将table中staleSlot处entry和下一个为null的entry之间的
      // entry重新进行hash放置到新的位置
      // 遇到的entry的key为null则删除该entry
      Entry e;
      int i;
      for (i = nextIndex(staleSlot, len);
  (e = tab[i]) != null;
  i = nextIndex(i, len)) {
 // e是下一个entry
 ThreadLocal k = e.get();
 if (k == null) {
 	// 若entry的key为null,则删除
   e.value = null;
   tab[i] = null;
   size--;
 } else {
 	// entry的key不为null,需要将entry放到新的位置
   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.
     // tab[h]不为null则发生冲突,继续寻找下一个位置
     while (tab[h] != null)
h = nextIndex(h, len);
     tab[h] = e;
   }
 }
      }
      return i;
    }
set方法

ThreadLocal的set方法定义如下:

  
  public void set(T value) {
    Thread t = Thread.currentThread();
    // 获取当前线程的threadLocals
    ThreadLocalMap map = getMap(t);
    // threadLocals不为null直接设置新值
    if (map != null) {
      map.set(this, value);
    } else {
    	// threadLocals为null则需要创建ThreadLocalMap对象并赋给
    	// Thread的threadLocals成员
      createMap(t, value);
    }
  }

createMap前面已经分析过,接下来分析ThreadLocalMap的set方法

ThreadLocalMap的set方法

ThreadLocalMap的set方法定义如下,将当前的ThreadLocal对象作为key,传入的value为值,用key和value创建entry,放到table中适当的位置:

    
    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;
      // 用key计算entry在table中的位置
      int i = key.threadLocalHashCode & (len-1);

			// tab[i]不为null的话,则第i个位置已经存在有效的entry,需要继续
			// 往后寻找新的位置
      for (Entry e = tab[i];
  e != null;
  e = tab[i = nextIndex(i, len)]) {
 ThreadLocal k = e.get();
				
				// 找到与key相同的entry,直接更新value的值
 if (k == key) {
   e.value = value;
   return;
 }
				
				// 遇到key为null的entry,删除该entry
 if (k == null) {
   replaceStaleEntry(key, value, i);
   return;
 }
      }

			// 此时第i个位置entry为null,将新entry放置到这个位置
      tab[i] = new Entry(key, value);
      int sz = ++size;
      // 试图清除无效的entry,若清除失败并且table中有效entry个数
      // 大于threshold,这进行rehash操作
      if (!cleanSomeSlots(i, sz) && sz >= threshold)
 rehash();
    }
replaceStaleEntry方法

replaceStaleEntry的作用是用set方法传过来的key和value构造entry,将这个entry放到staleSlot后面的某个位置:

    
    private void replaceStaleEntry(ThreadLocal key, Object value,
      int staleSlot) {
      Entry[] tab = table;
      int len = tab.length;
      Entry e;

      // Back up to check for prior stale entry in current run.
      // We clean out whole runs at a time to avoid continual
      // incremental rehashing due to garbage collector freeing
      // up refs in bunches (i.e., whenever the collector runs).
      // 从staleSlot往前找到第一个key为null的entry的位置
      int slotToExpunge = staleSlot;
      for (int i = prevIndex(staleSlot, len);
  (e = tab[i]) != null;
  i = prevIndex(i, len))
 if (e.get() == null)
   slotToExpunge = i;

      // Find either the key or trailing null slot of run, whichever
      // occurs first
      // 从staleSlot位置往后寻找
      for (int i = nextIndex(staleSlot, len);
  (e = tab[i]) != null;
  i = nextIndex(i, len)) {
 ThreadLocal k = e.get();

 // If we find key, then we need to swap it
 // with the stale entry to maintain hash table order.
 // The newly stale slot, or any other stale slot
 // encountered above it, can then be sent to expungeStaleEntry
 // to remove or rehash all of the other entries in run.
 // 若k与key相同,则直接更新value
 if (k == key) {
   e.value = value;
					// 将原来staleSlot位置的entry放置到第i个位置,此时tab[i]处的entry的key为null
   tab[i] = tab[staleSlot];
   tab[staleSlot] = e;

   // Start expunge at preceding stale entry if it exists
   // 从staleSlot处往前未找到key为null的entry
   if (slotToExpunge == staleSlot)
   	// tab[i]处entry的key为null,也即tab[slotToExpunge]处entry的key为null
     slotToExpunge = i;
   // 清除slotToExpunge位置的entry并进行rehash操作.....
   cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
   return;
 }

 // If we didn't find stale entry on backward scan, the
 // first stale entry seen while scanning for key is the
 // first still present in the run.
 if (k == null && slotToExpunge == staleSlot)
   slotToExpunge = i;
      }

      // If key not found, put new entry in stale slot
      tab[staleSlot].value = null;
      tab[staleSlot] = new Entry(key, value);

      // If there are any other stale entries in run, expunge them
      if (slotToExpunge != staleSlot)
 cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
    }

以下源码只可意会,不可言传…不再做说明

cleanSomeSlots方法

cleanSomeSlots方法:

    
    private boolean cleanSomeSlots(int i, int n) {
      boolean removed = false;
      Entry[] tab = table;
      int len = tab.length;
      do {
 i = nextIndex(i, len);
 Entry e = tab[i];
 if (e != null && e.get() == null) {
   n = len;
   removed = true;
   i = expungeStaleEntry(i);
 }
      } while ( (n >>>= 1) != 0);
      return removed;
    }
rehash方法

rehash方法:

    
    private void rehash() {
      expungeStaleEntries();

      // Use lower threshold for doubling to avoid hysteresis
      if (size >= threshold - threshold / 4)
 resize();
    }
expungeStaleEntries方法

expungeStaleEntries方法:

    
    private void expungeStaleEntries() {
      Entry[] tab = table;
      int len = tab.length;
      for (int j = 0; j < len; j++) {
 Entry e = tab[j];
 if (e != null && e.get() == null)
   expungeStaleEntry(j);
      }
    }
resize方法

resize方法:

    
    private void resize() {
      Entry[] oldTab = table;
      int oldLen = oldTab.length;
      int newLen = oldLen * 2;
      Entry[] newTab = new Entry[newLen];
      int count = 0;

      for (Entry e : oldTab) {
 if (e != null) {
   ThreadLocal k = e.get();
   if (k == null) {
     e.value = null; // Help the GC
   } else {
     int h = k.threadLocalHashCode & (newLen - 1);
     while (newTab[h] != null)
h = nextIndex(h, newLen);
     newTab[h] = e;
     count++;
   }
 }
      }

      setThreshold(newLen);
      size = count;
      table = newTab;
    }

更多java相关内容感兴趣的读者可查看本站专题:《Java进程与线程操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/136980.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号