Are there thread group-local variables in Java?

前端 未结 3 1493
失恋的感觉
失恋的感觉 2020-12-29 13:40

I am looking for a class similar to ThreadLocal which would work on thread groups instead of threads.

If there is not such a class (in some open source library) how

3条回答
  •  误落风尘
    2020-12-29 14:34

    I would store a value holder in a thread local and initialize it to the same value holder for all threads of the same group.

     public class ThreadGroupLocal extends ThreadLocal {
         private static class ValueHolder {
             public Object value;
         }
         // Weak & Concurrent would be even the better, but Java API wont offer that :(
         private static ConcurrentMap map = new ConcurrentHashMap;
         private static ValueHolder valueHolderForThread(Thread t) {
             map.putIfAbsent(t.getThreadGroup(), new ValueHolder());
             return map.get(t.getThreadGroup());
         }
         @Override 
         protected ValueHolder initialValue() {
             return valueHolderForThread(Thread.currentThread());
         }
         public T getValue() { (T) get().value; }
         public void setValue(T value) { get().value = value; }
     }
    

    and then use

     ThreadGroupLocal groupLocal = new ThreadGroupLocal();
     groupLocal.setValue("foo");
     //...
     String foo = groupLocal.getValue();
    

    That does (expect for the initialization) perform exactly like a thread local.

提交回复
热议问题