Java InheritableThreadLocal用法詳細(xì)介紹
簡介
本文介紹InheritableThreadLocal的用法。
ThreadLocal可以將數(shù)據(jù)綁定當(dāng)前線程,如果希望當(dāng)前線程的ThreadLocal的數(shù)據(jù)被子線程使用,實現(xiàn)方式就會相當(dāng)困難(需要用戶自己在代碼中傳遞)。
InheritableThreadLocal可以方便地讓子線程自動獲取父線程ThreadLocal的數(shù)據(jù)。
ThreadLocal和InheritableThreadLocal都要注意,用完后要調(diào)用其remove()方法,不然可能導(dǎo)致內(nèi)存泄露或者產(chǎn)生臟數(shù)據(jù)。
問題復(fù)現(xiàn)
代碼
package com.example.a;
public class Demo {
private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
threadLocal.set("hello");
System.out.println("主線程獲取的value:" + threadLocal.get());
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
String value = threadLocal.get();
System.out.println("子線程獲取的value:" + value);
// 一定要remove,不然可能導(dǎo)致內(nèi)存泄漏
threadLocal.remove();
}
});
thread.start();
}
}結(jié)果(子線程無法獲取父線程設(shè)置的值)
主線程獲取的value:hello
子線程獲取的value:null
解決方案
只需要將ThreadLocal變成InheritableThreadLocal。
代碼
package com.example.a;
public class Demo {
private static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
public static void main(String[] args) {
inheritableThreadLocal.set("hello");
System.out.println("主線程獲取的value:" + inheritableThreadLocal.get());
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
String value = inheritableThreadLocal.get();
System.out.println("子線程獲取的value:" + value);
// 一定要remove,不然可能導(dǎo)致內(nèi)存泄漏
inheritableThreadLocal.remove();
}
});
thread.start();
}
}結(jié)果(子線程可以獲取父線程設(shè)置的值)
主線程獲取的value:hello
子線程獲取的value:hello
源碼分析
源碼查看
InheritableThreadLocal的源代碼:
package java.lang;
import java.lang.ref.*;
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
protected T childValue(T parentValue) {
return parentValue;
}
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}這個類繼承了ThreadLocal,并且重寫了getMap和createMap方法,區(qū)別是:InheritableThreadLocal將 ThreadLocal 中的 threadLocals 換成了 inheritableThreadLocals,這兩個變量都是ThreadLocalMap類型,并且都是Thread類的屬性。
InheritableThreadLocal為什么能拿到父線程中的ThreadLocal值?
1.InheritableThreadLocal的get方法
InheritableThreadLocal獲取值先調(diào)用了get方法,所以我們直接看看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();
}可以看出,get方法和ThreadLocal中是一樣的,唯一有區(qū)別的就是其中的getMap方法重寫了,返回的是inheritableThreadLocals屬性。這個屬性也是一個ThreadLocalMap類型的變量。那么可以推斷:是在某處將父線程中的ThreadLocal值賦值到了子線程的inheritableThreadLocals中。
2.子線程inheritableThreadLocals的賦值過程
private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name.toCharArray();
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
if (security != null) {
g = security.getThreadGroup();
}
if (g == null) {
g = parent.getThreadGroup();
}
}
g.checkAccess();
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
//1. 這邊先判斷了父線程中inheritableThreadLocals屬性是否為空,不為空的話就復(fù)制給子線程
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}注意
一旦子線程被創(chuàng)建以后,再操作父線程中的ThreadLocal變量,那么子線程是不能感知的。因為父線程和子線程還是擁有各自的ThreadLocalMap,只是在創(chuàng)建子線程的“一剎那”將父線程的ThreadLocalMap復(fù)制給子線程,后續(xù)兩者就沒啥關(guān)系了。
其他網(wǎng)址傳送門
到此這篇關(guān)于Java InheritableThreadLocal用法詳細(xì)介紹的文章就介紹到這了,更多相關(guān)Java InheritableThreadLocal內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java Swing組件文件選擇器JFileChooser簡單用法示例
這篇文章主要介紹了Java Swing組件文件選擇器JFileChooser簡單用法,結(jié)合實例形式分析了Swing組件中的文件選擇器JFileChooser的簡單使用方法,需要的朋友可以參考下2017-11-11
Springboot項目長時間不進(jìn)行接口操作,提示HikariPool-1警告的解決
這篇文章主要介紹了Springboot項目長時間不進(jìn)行接口操作,提示HikariPool-1警告的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
JavaWeb學(xué)習(xí)筆記之Filter和Listener
這篇文章主要給大家介紹了關(guān)于JavaWeb學(xué)習(xí)筆記之Filter和Listener的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
springboot+vue實現(xiàn)阿里云oss上傳的示例代碼
文件上傳是常用的功能,本文主要介紹了springboot+vue實現(xiàn)阿里云oss上傳的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-06-06
Redis原子計數(shù)器incr,防止并發(fā)請求操作
這篇文章主要介紹了Redis原子計數(shù)器incr,防止并發(fā)請求操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

