代码之家  ›  专栏  ›  技术社区  ›  Andrey Adamovich

带有键回调读取线程局部变量的静态哈希表

  •  0
  • Andrey Adamovich  · 技术社区  · 16 年前

    问题是我有一个旧的Web服务库,它有一个全局选项的哈希表,它与请求选项的哈希表相结合。我不能影响请求代码,但是我可以设置全局哈希表。我只是好奇是否有一种简单的方法来实现哈希表类的扩展,该类将对一些键执行回调,以读取一些线程局部变量而不是其原始值?

    编辑 :我忘了说我一定要去JDK 1.4.2。

    3 回复  |  直到 16 年前
        1
  •  5
  •   Aaron Digulla    16 年前

    可以创建派生自 Hashtable 并覆盖 get() 方法。

    基于twolfe18规范:

    public class MyHashMap<K, V> extends HashMap<K, V> {
      TheadLocal special = new TheadLocal ();
    
      public MyHashMap<K, V>() {
        super();
      }
    
      public V get(K key) {
        if ("special".equals (key))
           return special.get ();
    
        return super.get(key);
      }
    }
    

    要设置值,请使用 map.special.set(value) .每个线程的值不同。

        2
  •  3
  •   twolfe18    16 年前

    在对Aaron的回应的评论中,格式很糟糕,所以这里是:

    public class MyHashMap<K, V> extends HashMap<K, V> {
    
      public MyHashMap<K, V>() {
        super();
      }
    
      public V get(K key) {
        // check the key or whatever you need to do
        V value = super.get(key);
        // check the value or whatever you need to do
        return value;
      }
    
    }
    
        3
  •  0
  •   Andrey Adamovich    16 年前

    下面是我最终使用的代码:

    package util;
    
    import java.util.Hashtable;
    
    public class SingleThreadLocalHashtable extends Hashtable {
    
        /** Class version. */
        private static final long serialVersionUID = 1L;
    
        private ThreadLocal holder = new ThreadLocal();
    
        private String specialKey;
    
        public SingleThreadLocalHashtable(String specialKey) {
            super();
            this.holder.set(null);
            this.specialKey = specialKey;
        }
    
        public synchronized Object get(Object key) {
            if ((specialKey != null) && specialKey.equals(key)) {
                return holder.get();
            }
            return super.get(key);
        }
    
        public synchronized Object put(Object key, Object value) {
            if ((specialKey != null) && specialKey.equals(key)) {
                holder.set(value);
            }
            return super.put(key, value);
        }
    
    }