From cec7f4017d598e61865be1a37e4df8cee5f968ea Mon Sep 17 00:00:00 2001 From: Jonathan Shook Date: Mon, 13 Sep 2021 09:42:21 -0500 Subject: [PATCH] centralize ObjectCache into core templating API --- .../engine/api/templating/ObjectCache.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 adapters-api/src/main/java/io/nosqlbench/engine/api/templating/ObjectCache.java 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); + } +}