From d506ccdcaf52a246adbbf27a7022d4e2602b83a7 Mon Sep 17 00:00:00 2001 From: Ashley Frieze Date: Thu, 24 Aug 2017 09:42:01 +0100 Subject: [PATCH] Removed thread-segregation from `Variable` and `let`. --- .../com/greghaskins/spectrum/Variable.java | 6 +++--- src/test/java/specs/LetSpecs.java | 18 ++++++++++++++++++ src/test/java/specs/VariableSpecs.java | 11 +++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) 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())); + }); + }); }