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 would you implement it? Some better idea than having thread groups in WeakHashMap?
I am implementing a debugging framework tunable in run-time with various parameters in global, per-thread and per-thread group contexts. As a very simple example, you can have a reporting statement:
debug.log( category, message);
and specify that the log entry with that specific category will be displayed only when called by a thread in group of threads servicing network requests.
Answer
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<T> extends ThreadLocal<ValueHolder> { private static class ValueHolder { public Object value; } // Weak & Concurrent would be even the better, but Java API wont offer that :( private static ConcurrentMap<ThreadGroup, ValueHolder> map = new ConcurrentHashMap<ThreadGroup, ValueHolder>; 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<String> groupLocal = new ThreadGroupLocal<String>(); groupLocal.setValue("foo"); //... String foo = groupLocal.getValue();
That does (expect for the initialization) perform exactly like a thread local.