package io.vertx.sqlclient.impl.cache;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.sqlclient.impl.PreparedStatement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class LruCache<K, V> extends LinkedHashMap<K, V> {
List<V> removed;
private final int capacity;
public LruCache(int capacity) {
super(capacity, 0.75f, true);
this.capacity = capacity;
}
public V evict() {
Iterator<V> it = values().iterator();
if (it.hasNext()) {
V value = it.next();
it.remove();
return value;
} else {
return null;
}
}
public List<V> cache(K key, V value) {
put(key, value);
if (removed != null) {
List<V> evicted = removed;
removed = null;
return evicted;
} else {
return Collections.emptyList();
}
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
boolean evict = size() > capacity;
if (evict) {
if (removed == null) {
removed = new ArrayList<>();
}
removed.add(eldest.getValue());
return true;
} else {
return false;
}
}
}