diff --git a/src/main/java/com/greghaskins/spectrum/Variable.java b/src/main/java/com/greghaskins/spectrum/Variable.java index f574a23..755236b 100644 --- a/src/main/java/com/greghaskins/spectrum/Variable.java +++ b/src/main/java/com/greghaskins/spectrum/Variable.java @@ -10,7 +10,7 @@ */ public final class Variable implements Supplier { - private ThreadLocal value = new ThreadLocal<>(); + private T value; /** * Create a Variable with a {@code null} initial value. @@ -33,7 +33,7 @@ public Variable(final T value) { */ @Override public T get() { - return this.value.get(); + return this.value; } /** @@ -42,6 +42,6 @@ public T get() { * @param value new value */ public void set(final T value) { - this.value.set(value); + this.value = value; } } diff --git a/src/test/java/specs/LetSpecs.java b/src/test/java/specs/LetSpecs.java index 315ca00..fbe311a 100644 --- a/src/test/java/specs/LetSpecs.java +++ b/src/test/java/specs/LetSpecs.java @@ -182,8 +182,26 @@ public class LetSpecs { assertThat(result.getFailures().get(1).getMessage(), is("Bong!")); }); }); + }); + + describe("let across multiple threads", () -> { + final Supplier> listSupplier = let(ArrayList::new); + it("can share the object with worker thread", () -> { + // when the supplier's object has something added to it + listSupplier.get().add("Hello world"); + // used as a box for the integer + AtomicInteger atomicInteger = new AtomicInteger(); + // when we access the object within a worker thread + Thread thread = new Thread(() -> atomicInteger.set(listSupplier.get().size())); + thread.start(); + thread.join(); + + // then the worker thread saw the same object as the outer thread + // then the worker thread saw the same object as the outer thread + assertThat(atomicInteger.get(), is(1)); + }); }); }); } diff --git a/src/test/java/specs/VariableSpecs.java b/src/test/java/specs/VariableSpecs.java index a016ddc..402b659 100644 --- a/src/test/java/specs/VariableSpecs.java +++ b/src/test/java/specs/VariableSpecs.java @@ -48,6 +48,17 @@ public class VariableSpecs { assertNull(name.get()); }); + it("has the same value across threads", () -> { + final Variable outerVariable = new Variable<>("outer"); + final Variable whatWorkerThreadSees = new Variable<>(); + + Thread worker = new Thread(() -> whatWorkerThreadSees.set(outerVariable.get())); + worker.start(); + worker.join(); + + assertThat(whatWorkerThreadSees.get(), is(outerVariable.get())); + }); + }); }