convex.core.util.SoftCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of convex-core Show documentation
Show all versions of convex-core Show documentation
Convex core libraries and common utilities
The newest version!
package convex.core.util;
import java.lang.ref.SoftReference;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.Set;
import java.util.WeakHashMap;
/**
* Cache with weak keys and soft referenced values
*/
public class SoftCache extends AbstractMap {
private WeakHashMap> cache=new WeakHashMap>();
public V get(Object key) {
SoftReference sr=getSoftReference(key);
if (sr==null) return null;
return sr.get();
}
public SoftReference getSoftReference(Object key) {
return cache.get(key);
}
@Override
public V put(K key, V value) {
SoftReference sr=new SoftReference<>(value);
cache.put(key, sr);
return null;
}
public SoftReference putReference(K key, SoftReference valueRef) {
return cache.put(key, valueRef);
}
@Override
public Set> entrySet() {
HashSet> result=new HashSet>();
for (Entry> e: cache.entrySet()) {
V val=e.getValue().get();
if (val!=null) {
result.add(new AbstractMap.SimpleEntry<>(e.getKey(),val));
}
}
return result;
}
}