This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/client/src/main/java/envoy/client/data/Cache.java

72 lines
1.7 KiB
Java

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 <T> the type of cached elements
* @author Kai S. K. Engelbart
* @since Envoy Client v0.3-alpha
*/
public final class Cache<T> implements Consumer<T>, Serializable {
private final Queue<T> elements = new LinkedList<>();
private transient Consumer<T> 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<T> 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();
}
}