Java中是否存在线程组本地变量? [英] Are there thread group-local variables in Java?

查看:210
本文介绍了Java中是否存在线程组本地变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个类似于ThreadLocal的类,它可以在线程组而不是线程上工作。

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

如果没有这样的类(在某些开源库中)你会如何实现它?比在WeakHashMap中拥有线程组更好的想法?

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.

推荐答案

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

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.

这篇关于Java中是否存在线程组本地变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆