66 lines
1.8 KiB
Java
66 lines
1.8 KiB
Java
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.
|
|
* <p>
|
|
* Project: <strong>envoy-client</strong><br>
|
|
* File: <strong>Cache.java</strong><br>
|
|
* Created: <strong>6 Feb 2020</strong><br>
|
|
*
|
|
* @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();
|
|
}
|
|
}
|