且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java中是否存在线程组本地变量?

更新时间:2023-11-13 18:10:10

我会将一个值持有者存储在本地线程中并将其初始化为相同的值持有者同一组的所有线程。

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; }
 }

然后使用

 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.