package envoy.client.data; import java.io.Serializable; import java.util.*; import java.util.function.Consumer; import java.util.logging.*; import envoy.util.EnvoyLog; /** * Stores elements in a queue to process them later. * * @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(); } /** * Clears this cache of all stored elements. * * @since Envoy Client v0.2-beta */ public void clear() { elements.clear(); } }