59 lines
1.5 KiB
Java
59 lines
1.5 KiB
Java
|
package envoy.client.data;
|
||
|
|
||
|
import java.util.LinkedList;
|
||
|
import java.util.Queue;
|
||
|
import java.util.function.Consumer;
|
||
|
import java.util.logging.Logger;
|
||
|
|
||
|
import envoy.client.util.EnvoyLog;
|
||
|
|
||
|
/**
|
||
|
* Stores elements in a queue to process them later.<br>
|
||
|
* <br>
|
||
|
* 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 v0.3-alpha
|
||
|
*/
|
||
|
public class Cache<T> implements Consumer<T> {
|
||
|
|
||
|
private final Queue<T> elements = new LinkedList<>();
|
||
|
private Consumer<T> processor;
|
||
|
|
||
|
private static final Logger logger = EnvoyLog.getLogger(Cache.class.getSimpleName());
|
||
|
|
||
|
/**
|
||
|
* Adds an element to the cache.
|
||
|
*
|
||
|
* @param element the element to add
|
||
|
* @since Envoy v0.3-alpha
|
||
|
*/
|
||
|
@Override
|
||
|
public void accept(T element) {
|
||
|
logger.info(String.format("Adding element %s to cache", element));
|
||
|
elements.offer(element);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Sets the processor to which cached elements are relayed.
|
||
|
*
|
||
|
* @param processor the processor to set
|
||
|
* @since Envoy 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 v0.3-alpha
|
||
|
*/
|
||
|
public void relay() {
|
||
|
if (processor == null) throw new IllegalStateException("Processor is not defined");
|
||
|
elements.forEach(processor::accept);
|
||
|
}
|
||
|
}
|