java get all threadlocal from thread

Posted   智信智爱智强不息

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java get all threadlocal from thread相关的知识,希望对你有一定的参考价值。

 

 

public void mytest() {
long start = System.currentTimeMillis();
Thread thread = Thread.currentThread();

Field threadLocalsField = null;
try {
threadLocalsField = Thread.class.getDeclaredField("threadLocals");

threadLocalsField.setAccessible(true);

Class threadLocalMapKlazz = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
Field tableField = threadLocalMapKlazz.getDeclaredField("table");
tableField.setAccessible(true);

Object table = tableField.get(threadLocalsField.get(thread));

int threadLocalCount = Array.getLength(table);
StringBuilder sb = new StringBuilder();
StringBuilder classSb = new StringBuilder();


int leakCount = 0;

for (int i = 0; i < threadLocalCount; i++) {
Object entry = Array.get(table, i);
if (entry != null) {
Field valueField = entry.getClass().getDeclaredField("value");
valueField.setAccessible(true);
Object value = valueField.get(entry);
if (value != null) {
classSb.append(value.getClass().getName()).append(", ");

} else {
classSb.append("null, ");
}
leakCount++;
}
}

sb.append("possible ThreadLocal leaks: ")
.append(leakCount)
.append(" of ")
.append(threadLocalCount)
.append(" = [")
.append(classSb.substring(0, classSb.length() - 2))
.append("] ");

log.warn(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
long cost = end - start;
log.info("获取ThreadLocal耗时:{}", cost);



结果: possible ThreadLocal leaks: 9 of 16 = [java.util.Collections$SynchronizedMap, null,
java.lang.Boolean, java.lang.Boolean, null, java.lang.Integer, java.lang.Boolean, brave.propagation.TraceContext, null] 

以上是关于java get all threadlocal from thread的主要内容,如果未能解决你的问题,请参考以下文章

java多线程进阶ThreadLocal

java多线程进阶ThreadLocal

ThreadLocal源码解析-Java8

Java学习2 (ThreadLocal)

java ThreadLocal

java多线程17:ThreadLocal源码剖析