Skip to content

Commit

Permalink
Use soft references for values instead of weak references in the Weak…
Browse files Browse the repository at this point in the history
…WeakMap, so that values are only finalised when there is enough memory pressure.
  • Loading branch information
Gohla committed Jun 11, 2014
1 parent 7df8fb5 commit f337ff0
Showing 1 changed file with 12 additions and 13 deletions.
@@ -1,6 +1,6 @@
package org.strategoxt.imp.runtime;

import java.lang.ref.WeakReference;
import java.lang.ref.SoftReference;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
Expand All @@ -15,13 +15,11 @@
*
* @see WeakHashMap
* @see WeakValueHashMap
*
* @author Lennart Kats <lennart add lclnet.nl>
*/
public class WeakWeakMap<K,V> implements Map<K,V> {
private final WeakHashMap<K, WeakReference<V>> map = new WeakHashMap<K, WeakReference<V>>();
public class WeakWeakMap<K, V> implements Map<K, V> {

private final WeakHashMap<K, SoftReference<V>> map = new WeakHashMap<K, SoftReference<V>>();

public WeakWeakMap() {
// Construct new instance
}
Expand All @@ -44,7 +42,7 @@ public Set<java.util.Map.Entry<K, V>> entrySet() {
}

public V get(Object key) {
WeakReference<V> ref = map.get(key);
SoftReference<V> ref = map.get(key);
return ref == null ? null : ref.get();
}

Expand All @@ -59,7 +57,7 @@ public Set<K> keySet() {
public V put(K key, V value) {
if (value == null)
throw new IllegalArgumentException("Value cannot be null");
WeakReference<V> existing = map.put(key, new WeakReference<V>(value));
SoftReference<V> existing = map.put(key, new SoftReference<V>(value));
return existing == null ? null : existing.get();
}

Expand All @@ -68,7 +66,7 @@ public void putAll(Map<? extends K, ? extends V> m) {
}

public V remove(Object key) {
WeakReference<V> existing = map.remove(key);
SoftReference<V> existing = map.remove(key);
return existing == null ? null : existing.get();
}

Expand All @@ -77,11 +75,12 @@ public int size() {
}

public Collection<V> values() {
Collection<WeakReference<V>> results = map.values();
Collection<SoftReference<V>> results = map.values();
Set<V> copy = new HashSet<V>(results.size());
for (WeakReference<V> resultRef : results) {
for (SoftReference<V> resultRef : results) {
V result = resultRef == null ? null : resultRef.get();
if (result != null) copy.add(result);
if (result != null)
copy.add(result);
}
return copy;
}
Expand Down

0 comments on commit f337ff0

Please sign in to comment.