package envoy.client.data;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Queue;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import envoy.util.EnvoyLog;
/**
* Stores elements in a queue to process them later.
*
* Project: envoy-client
* File: Cache.java
* Created: 6 Feb 2020
*
* @param the type of cached elements
* @author Kai S. K. Engelbart
* @since Envoy Client v0.3-alpha
*/
public final class Cache implements Consumer, Serializable {
private final Queue elements = new LinkedList<>();
private transient Consumer processor;
private static final Logger logger = EnvoyLog.getLogger(Cache.class);
private static final long serialVersionUID = 0L;
/**
* Adds an element to the cache.
*
* @param element the element to add
* @since Envoy Client v0.3-alpha
*/
@Override
public void accept(T element) {
logger.log(Level.FINE, String.format("Adding element %s to cache", element));
elements.offer(element);
}
@Override
public String toString() { return String.format("Cache[elements=" + elements + "]"); }
/**
* Sets the processor to which cached elements are relayed.
*
* @param processor the processor to set
* @since Envoy Client v0.3-alpha
*/
public void setProcessor(Consumer processor) { this.processor = processor; }
/**
* Relays all cached elements to the processor.
*
* @throws IllegalStateException if the processor is not initialized
* @since Envoy Client v0.3-alpha
*/
public void relay() {
if (processor == null) throw new IllegalStateException("Processor is not defined");
elements.forEach(processor::accept);
elements.clear();
}
}