diff --git a/adapters-api/src/main/java/io/nosqlbench/engine/api/templating/ObjectCache.java b/adapters-api/src/main/java/io/nosqlbench/engine/api/templating/ObjectCache.java new file mode 100644 index 000000000..ba978afae --- /dev/null +++ b/adapters-api/src/main/java/io/nosqlbench/engine/api/templating/ObjectCache.java @@ -0,0 +1,27 @@ +package io.nosqlbench.engine.api.templating; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +/** + * An object cache to memoize returned objects into a concurrent hash map by name. + * This is meant to be used when you want to lazily initialize an instance of something + * by name that is likely to be re-used over the lifetime of an owning object. + * + * @param The type of object. + */ +public class ObjectCache implements Function { + + private final ConcurrentHashMap cache = new ConcurrentHashMap<>(); + + private final Function newInstanceFunction; + + public ObjectCache(Function newInstanceFunction) { + this.newInstanceFunction = newInstanceFunction; + } + + @Override + public T apply(String name) { + return cache.computeIfAbsent(name, newInstanceFunction); + } +}