有没有办法迭代或复制Java ThreadLocal的所有值? [英] Is there no way to iterate over or copy all the values of a Java ThreadLocal?

查看:107
本文介绍了有没有办法迭代或复制Java ThreadLocal的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:

static ThreadLocal<MyType> threadLocalMyType = ...

我想说的是:

for (ThreadLocalEntry e: threadLocalMyType.getMapLikeThing() {
    // Thread t = e.getKey(); 
    // I don't need the thread value right now, but it might be useful for 
    // something else. 

    MyType theMyType = e.getValue();
    // [...do something with theMyType...]
}


推荐答案

一种方法是手动处理:


  • 使用 ThreadLocal的包装器(扩展)

  • 每当设置一个值时,保持一个( static 地图的主题和价值

  • use a wrapper of ThreadLocal (extend it)
  • whenever a value is set, keep a (static) Map of Threads and values

或者,有一些反思( getDeclaredMethod() setAccessible(true)),您可以:

Alternatively, with some reflection (getDeclaredMethod() and setAccessible(true)), you can:


  • call Thread.getThreads()

  • call yourThreadLocal.ge tMap(thread)(对于上述每个线程)

  • 调用 map.getEntry(yourThreadLocal)

  • call Thread.getThreads()
  • call yourThreadLocal.getMap(thread) (for each of the above threads)
  • call map.getEntry(yourThreadLocal)

第一个是更优先的。

这篇关于有没有办法迭代或复制Java ThreadLocal的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆