shz.core.cache.SimpleCache Maven / Gradle / Ivy
package shz.core.cache;
import shz.core.ToList;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
@SuppressWarnings("unchecked")
public final class SimpleCache extends LocalCache {
private final ConcurrentHashMap> cache;
public SimpleCache(int capacity, RefType refType, ReferenceQueue queue) {
super(refType, queue);
cache = new ConcurrentHashMap<>(capacity);
}
public SimpleCache(int capacity, RefType refType) {
this(capacity, refType, new ReferenceQueue<>());
}
public SimpleCache(int capacity) {
this(capacity, RefType.SOFT);
}
public SimpleCache() {
this(128);
}
@Override
public V get(K key) {
Reference ref = cache.get(key);
if (ref == null) return null;
V v = ref.get();
if (v == null) cache.remove(key);
return v;
}
@Override
public V get(K key, Supplier> supplier, long expireMillis, long nullKeyExpireMillis, long timeoutMillis) {
Reference ref = cache.get(key);
if (ref != null) {
V v = ref.get();
if (v != null) return v;
}
V val = (V) supplier.get();
set(key, val, expireMillis, nullKeyExpireMillis);
return val;
}
@Override
public void set(K key, V val, long expireMillis, long nullKeyExpireMillis) {
cache.put(key, getReference(val));
}
@Override
public void delete(K key) {
Reference ref = cache.get(key);
if (ref == null) return;
if (!ref.isEnqueued()) ref.enqueue();
cache.remove(key);
}
@Override
public boolean hasKey(K key) {
return cache.containsKey(key);
}
@Override
public long getExpire(K key) {
return super.getExpire(key);
}
@Override
public boolean expire(K key, long expireMillis) {
return super.expire(key, expireMillis);
}
@Override
public boolean persist(K key) {
return super.persist(key);
}
@Override
public int size() {
return cache.size();
}
@Override
public List keys() {
return ToList.explicitCollect(cache.keySet().stream(), size());
}
@Override
public void clear() {
cache.clear();
}
}