Question

The problem is that I have an old web service library that has a hashtable of global options which it combines with hashtable of request options. I cann't influence request code, but I can set the global hashtable. And I was just curious if there is a simple way to implement an extention to Hashtable class that will perform a callback for some of the key to read some thread-local variable instead of its original value?

EDIT: I forgot to mention that I'm bound to JDK 1.4.2.

Was it helpful?

Solution

You can create a new class that derives from Hashtable and override the get() method.

Building on the code of 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);
  }
}

To set the value, use map.special.set(value). The value will be different per thread.

OTHER TIPS

the formatting came out terrible in a comment on Aaron's response so here it is:

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

}

Here is the code I used eventually:

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top