ThreadLocal value access across different threads

前端 未结 5 1069
南笙
南笙 2020-12-09 19:29

Given that a ThreadLocal variable holds different values for different threads, is it possible to access the value of one ThreadLocal variable from another thread?

5条回答
  •  醉酒成梦
    2020-12-09 19:58

    ThreadLocalMap CAN be access via Reflection and Thread.class.getDeclaredField("threadLocals") setAccssible(true), and so on. Do not do that, though. The map is expected to be accessed by the owning thread only and accessing any value of a ThreadLocal is a potential data race.

    However, if you can live w/ the said data races, or just avoid them (way better idea). Here is the simplest solution. Extend Thread and define whatever you need there, that's it:

    ThreadX extends Thread{
      int extraField1;
      String blah2; //and so on
    }
    

    That's a decent solution that doesn't relies on WeakReferences but requires that you create the threads. You can set like that ((ThreadX)Thread.currentThread()).extraField1=22

    Make sure you do no exhibit data races while accessing the fields. So you might need volatile, synchronized and so on.

    Overall Map is a terribad idea, never keep references to object you do not manage/own explicitly; especially when it comes to Thread, ThreadGroup, Class, ClassLoader... WeakHashMap is slightly better, however you need to access it exclusively (i.e. under lock) which might damper the performance in heavily multithreaded environment. WeakHashMap is not the fastest thing in the world.

    ConcurrentMap, Object> would be better but you need a WeakRef that has equals and hashCode...

提交回复
热议问题