All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.g2forge.alexandria.java.associative.cache.Cache Maven / Gradle / Ivy

There is a newer version: 0.0.18
Show newest version
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 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;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy