org.snapscript.common.SoftCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of snap Show documentation
Show all versions of snap Show documentation
Dynamic scripting for the JVM
package org.snapscript.common;
import java.lang.ref.SoftReference;
import java.util.Set;
public class SoftCache implements Cache {
private final Cache> cache;
public SoftCache() {
this(100);
}
public SoftCache(int capacity) {
this.cache = new LeastRecentlyUsedCache>(capacity);
}
@Override
public Set keySet() {
return cache.keySet();
}
@Override
public V take(K key) {
SoftReference reference = cache.take(key);
if(reference != null) {
return reference.get();
}
return null;
}
@Override
public V fetch(K key) {
SoftReference reference = cache.fetch(key);
if(reference != null) {
return reference.get();
}
return null;
}
@Override
public void cache(K key, V value) {
SoftReference reference = new SoftReference(value);
if(value != null) {
cache.cache(key, reference);
}
}
@Override
public boolean contains(K key) {
SoftReference reference = cache.fetch(key);
if(reference != null) {
return reference.get() != null;
}
return false;
}
@Override
public boolean isEmpty() {
return cache.isEmpty();
}
@Override
public void clear() {
cache.clear();
}
@Override
public int size() {
return cache.size();
}
@Override
public String toString() {
return String.valueOf(cache);
}
}