0

I wanted to implement SoftHashMap based on Java SoftReference and HashMap. Java docs, about WeakHashMap, say that keys are weak references rather than values. I was wondering what hashcode() would be used for put and pull functions of the underlying HashMap. I am assuming WeakHashMap put works like this: hashMap.put(new WeakReference(key), value); If this is true, how would the entry be found for a key.

Wouldn't it be better if values were wrapped in a WeakReference rather than keys?

Abidi
  • 7,846
  • 14
  • 43
  • 65
  • 2
    The source code for the Standard API classes comes with the JDK, just take a look. – Michael Borgwardt Jul 30 '11 at 21:03
  • Here's a link to the reference impl of [`WeakHashMap.put()`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/WeakHashMap.java#WeakHashMap.put%28java.lang.Object%2Cjava.lang.Object%29), and it doesn't follow the pattern you describe. – Mark Elliot Jul 30 '11 at 21:08
  • Other libs include weak-value maps and other variations for other purposes. – bmargulies Jul 30 '11 at 21:14
  • Readers might want to look at existing SoftHashMap implementations: http://stackoverflow.com/questions/264582/is-there-a-softhashmap-in-java – Blaisorblade Jul 26 '12 at 13:28

1 Answers1

3

If you look at this IBM article, you'll see that in the possible implementation they give:

public class WeakHashMap<K,V> implements Map<K,V> {

private static class Entry<K,V> extends WeakReference<K> 
  implements Map.Entry<K,V> {
    private V value;
    private final int hash;
    private Entry<K,V> next;
    ...
}

public V get(Object key) {
    int hash = getHash(key);
    Entry<K,V> e = getChain(hash);
    while (e != null) {
        K eKey= e.get();
        if (e.hash == hash && (key == eKey || key.equals(eKey)))
            return e.value;
        e = e.next;
    }
    return null;
}

put adds an Entry normally - but the Entry is a WeakReference referring to the Key object. If the Key is garbage collected, the Entry will eventually be cleared out by WeakHashMap's expungeStaleEntries() method, called every so often from other WeakHashMap operations.

Richard Campbell
  • 3,591
  • 23
  • 18