From a100f2a0d71f37320fe0f73be0d6d65094b60eb0 Mon Sep 17 00:00:00 2001 From: bculkin2442 Date: Thu, 28 Jul 2016 16:22:31 -0400 Subject: Ensure supplier don't materialize more than once --- BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java | 2 +- .../src/main/java/bjc/utils/data/LazyPair.java | 6 ++-- .../main/java/bjc/utils/data/SingleSupplier.java | 34 ++++++++++++++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) create mode 100644 BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java (limited to 'BJC-Utils2/src/main/java/bjc/utils') diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java index 112a503..22f948c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Lazy.java @@ -43,7 +43,7 @@ public class Lazy implements IHolder { * The source of a value to use */ public Lazy(Supplier supp) { - valueSupplier = supp; + valueSupplier = new SingleSupplier<>(supp); valueMaterialized = false; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java index e0b39cc..490c4fc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java @@ -29,7 +29,7 @@ public class LazyPair private boolean rightMaterialized; /** - * Create a new lazy pair, using the set value s + * Create a new lazy pair, using the set values * * @param leftVal * The value for the left side of the pair @@ -54,8 +54,8 @@ public class LazyPair */ public LazyPair(Supplier leftSupp, Supplier rightSupp) { - leftSupplier = leftSupp; - rightSupplier = rightSupp; + leftSupplier = new SingleSupplier<>(leftSupp); + rightSupplier = new SingleSupplier<>(rightSupp); leftMaterialized = false; rightMaterialized = false; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java new file mode 100644 index 0000000..016f492 --- /dev/null +++ b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java @@ -0,0 +1,34 @@ +package bjc.utils.data; + +import java.util.function.Supplier; + +public class SingleSupplier implements Supplier { + private Supplier source; + + private boolean gotten; + + private long id; + + private static long nextID = 0; + + public SingleSupplier(Supplier supp) { + source = supp; + + gotten = false; + + id = nextID++; + } + + @Override + public T get() { + if (gotten == true) { + throw new IllegalStateException( + "Attempted to get value more than once" + + " from single supplier #" + id); + } + + gotten = true; + + return source.get(); + } +} -- cgit v1.2.3