A method to clean ThreadLocal

   private void cleanThreadLocals() {
try {
// Get a reference to the thread locals table of the current thread
Thread thread = Thread.currentThread();
Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
Object threadLocalTable = threadLocalsField.get(thread); // Get a reference to the array holding the thread local variables inside the
// ThreadLocalMap of the current thread
Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
Field tableField = threadLocalMapClass.getDeclaredField("table");
tableField.setAccessible(true);
Object table = tableField.get(threadLocalTable); // The key to the ThreadLocalMap is a WeakReference object. The referent field of this object
// is a reference to the actual ThreadLocal variable
Field referentField = Reference.class.getDeclaredField("referent");
referentField.setAccessible(true); for (int i=0; i < Array.getLength(table); i++) {
// Each entry in the table array of ThreadLocalMap is an Entry object
// representing the thread local reference and its value
Object entry = Array.get(table, i);
if (entry != null) {
// Get a reference to the thread local object and remove it from the table
ThreadLocal threadLocal = (ThreadLocal)referentField.get(entry);
threadLocal.remove();
}
}
} catch(Exception e) {
// We will tolerate an exception here and just log it
throw new IllegalStateException(e);
}
}

最新文章

  1. List、Map、Set三个接口,存取元素时,各有什么特点?
  2. 盒子模型简单理解(box-sizing)
  3. javascript中正则表达式的基础语法
  4. BZOJ3853 : GCD Array
  5. php数据访问:pdo用法、事物回滚功能和放sql注入功能
  6. OSGi 的核心配置、动态化及问题
  7. Vmware为Ubuntu安装VmTools
  8. android SDK开发 -- TitleBar封装(一)
  9. Hibernate 性能优化之二级缓存
  10. 简单的方法来改善手机3G上网速度(2G转3G)
  11. openstack 网络架构 nova-network + neutron
  12. Hibernate常见问题 No row with the given identifier exists问题的解决办法及解决
  13. NFS+sersync+Keepalived高可用方案
  14. eclipse中创建一个maven项目
  15. centos7 编译安装greenplum5.7
  16. C#版[击败99.69%的提交] - Leetcode 242. 有效的同构异形词 - 题解
  17. 将python、pip 加入环境变量
  18. Hive 和 Mysql
  19. 各版本系统安装tesseract-ocr
  20. python学习之老男孩python全栈第九期_数据库day005知识点总结 —— MySQL数据库day5

热门文章

  1. 20165319第五周java学习笔记
  2. detailFormatter bootstrapTable
  3. Dijkstra算法之 Java详解
  4. Java内存管理-掌握类加载器的核心源码和设计模式(六)
  5. mac安装Elasticsearch
  6. 222. Getter与Setter
  7. Codeforces.578E.Walking(构造)
  8. Yahoo Programming Contest 2019.F.Pass(DP)
  9. BZOJ.4399.魔法少女LJJ(线段树合并)
  10. BZOJ.3784.树上的路径(点分治 贪心 堆)