Extending java's ThreadLocal to allow the values to be reset across all threads

前端 未结 3 892
迷失自我
迷失自我 2021-01-23 10:19

After looking at this question, I think I want to wrap ThreadLocal to add a reset behavior.

I want to have something similar to a ThreadLocal, with a method I can call f

3条回答
  •  有刺的猬
    2021-01-23 11:03

    It won't be a good idea to do that since the whole point of thread local storage is, well, thread locality of the value it contains - i.e. that you can be sure that no other thread than your own thread can touch the value. If other threads could touch your thread local value, it won't be "thread local" anymore and that will break the memory model contract of thread local storage.

    Either you have to use something other than ThreadLocal (e.g. a ConcurrentHashMap) to store the value, or you need to find a way to schedule an update on the threads in question.

    You could use google guava's map maker to create a static final ConcurrentWeakReferenceIdentityHashmap with the following type: Map> where the second map is a ConcurrentHashMap. That way you'd be pretty close to ThreadLocal except that you can iterate through the map.

提交回复
热议问题