com.g2forge.alexandria.java.associative.cache.Cache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ax-java Show documentation
Show all versions of ax-java Show documentation
Standard Java library and the basis of the ${alexandria.name} project.
package com.g2forge.alexandria.java.associative.cache;
import java.util.HashMap;
import java.util.Optional;
import java.util.function.Function;
import com.g2forge.alexandria.java.associative.IAssociation;
import com.g2forge.alexandria.java.associative.MapAssociation;
import lombok.Data;
@Data
public class Cache implements Function {
protected final Function super K, ? extends V> function;
protected final ICacheEvictionPolicy policy;
protected final IAssociation cache = new MapAssociation<>(new HashMap<>());
@Override
public V apply(K key) {
final Optional optional = cache.get(key, false);
if (optional.isPresent()) {
policy.access(false, key).forEach(cache::remove);
return optional.get();
}
final V retVal = function.apply(key);
policy.access(true, key).forEach(cache::remove);
cache.put(key, retVal);
return retVal;
}
}