@Override public int size() { expungeStaleEntries(); return hash.size(); }
@Override public V remove(Object key) { expungeStaleEntries(); SoftReference<V> result = hash.remove(key); if (result == null) { return null; } reverseLookup.remove(result); return result.get(); }
@Override public V put(K key, V value) { expungeStaleEntries(); SoftReference<V> softRef = new SoftReference<>(value, queue); reverseLookup.put(softRef, key); SoftReference<V> result = hash.put(key, softRef); if (result == null) { return null; } reverseLookup.remove(result); return result.get(); }
@Override public boolean containsKey(Object key) { expungeStaleEntries(); SoftReference<V> softRef = hash.get(key); if (softRef != null) { // From the SoftReference we get the value, which can be // null if it has been garbage collected V result = softRef.get(); if (result != null) { return true; } // If the value has been garbage collected, remove the // entry from the HashMap. hash.remove(key); reverseLookup.remove(softRef); } return false; } }
@Override public V get(Object key) { expungeStaleEntries(); V result = null; // We get the SoftReference represented by that key SoftReference<V> softRef = hash.get(key); if (softRef != null) { // From the SoftReference we get the value, which can be // null if it has been garbage collected result = softRef.get(); if (result == null) { // If the value has been garbage collected, remove the entry from the HashMap. removeElement(softRef); } } return result; }
/** * Returns a copy of the key/values in the map at the point of calling. However, setValue still sets the value in * the actual SoftHashMap. */ @Override public Set<Entry<K, V>> entrySet() { expungeStaleEntries(); Set<Entry<K, V>> result = new LinkedHashSet<>(); for (final Entry<K, SoftReference<V>> entry : hash.entrySet()) { final V value = entry.getValue().get(); if (value != null) { result.add(new Entry<K, V>() { @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return value; } @Override public V setValue(V v) { entry.setValue(new SoftReference<>(v, queue)); return value; } }); } } return result; }