Is there no way to iterate over or copy all the values of a Java ThreadLocal?

前端 未结 3 1235
执念已碎
执念已碎 2020-12-19 12:26

Context:

static ThreadLocal threadLocalMyType = ...

What i\'d like is to say something like:

for (ThreadLoc         


        
3条回答
  •  没有蜡笔的小新
    2020-12-19 12:35

    I came acrosss the same problem and after seeing the answers here, I decided to use a hybrid approach:

    public class PersistentThreadLocal extends ThreadLocal {
    
        final Map allValues;
        final Supplier valueGetter;
    
        public PersistentThreadLocal(Supplier initialValue) {
            this(0, initialValue);
        }
    
        public PersistentThreadLocal(int numThreads, Supplier initialValue) {
            allValues = Collections.synchronizedMap(
                numThreads > 0 ? new WeakHashMap<>(numThreads) : new WeakHashMap<>()
            );
            valueGetter = initialValue;
        }
    
        @Override
        protected T initialValue() {
            T value = valueGetter != null ? valueGetter.get() : super.initialValue();
            allValues.put(Thread.currentThread(), value);
            return value;
        }
    
        @Override
        public void set(T value) {
            super.set(value);
            allValues.put(Thread.currentThread(), value);
        }
    
        @Override
        public void remove() {
            super.remove();
            allValues.remove(Thread.currentThread());
        }
    
        public Collection getAll() {
            return allValues.values();
        }
    
        public void clear() {
            allValues.clear();
        }
    }
    

    EDIT: if you plan to use this with a ThreadPoolExecutor, change the WeakHashMap to a regular HashMap, otherwise strange things will happen!

提交回复
热议问题