Skip to content

Commit b7b920a

Browse files
authored
Merge pull request greghaskins#118 from ashleyfrieze/VariablesNotThreadLocal
Removed thread-segregation from `Variable` and `let`.
2 parents 3fb6960 + d506ccd commit b7b920a

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

src/main/java/com/greghaskins/spectrum/Variable.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
*/
1111
public final class Variable<T> implements Supplier<T> {
1212

13-
private ThreadLocal<T> value = new ThreadLocal<>();
13+
private T value;
1414

1515
/**
1616
* Create a Variable with a {@code null} initial value.
@@ -33,7 +33,7 @@ public Variable(final T value) {
3333
*/
3434
@Override
3535
public T get() {
36-
return this.value.get();
36+
return this.value;
3737
}
3838

3939
/**
@@ -42,6 +42,6 @@ public T get() {
4242
* @param value new value
4343
*/
4444
public void set(final T value) {
45-
this.value.set(value);
45+
this.value = value;
4646
}
4747
}

src/test/java/specs/LetSpecs.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,26 @@ public class LetSpecs {
182182
assertThat(result.getFailures().get(1).getMessage(), is("Bong!"));
183183
});
184184
});
185+
});
186+
187+
describe("let across multiple threads", () -> {
188+
final Supplier<List<String>> listSupplier = let(ArrayList::new);
189+
it("can share the object with worker thread", () -> {
190+
// when the supplier's object has something added to it
191+
listSupplier.get().add("Hello world");
185192

193+
// used as a box for the integer
194+
AtomicInteger atomicInteger = new AtomicInteger();
186195

196+
// when we access the object within a worker thread
197+
Thread thread = new Thread(() -> atomicInteger.set(listSupplier.get().size()));
198+
thread.start();
199+
thread.join();
200+
201+
// then the worker thread saw the same object as the outer thread
202+
// then the worker thread saw the same object as the outer thread
203+
assertThat(atomicInteger.get(), is(1));
204+
});
187205
});
188206
});
189207
}

src/test/java/specs/VariableSpecs.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,17 @@ public class VariableSpecs {
4848
assertNull(name.get());
4949
});
5050

51+
it("has the same value across threads", () -> {
52+
final Variable<String> outerVariable = new Variable<>("outer");
53+
final Variable<String> whatWorkerThreadSees = new Variable<>();
54+
55+
Thread worker = new Thread(() -> whatWorkerThreadSees.set(outerVariable.get()));
56+
worker.start();
57+
worker.join();
58+
59+
assertThat(whatWorkerThreadSees.get(), is(outerVariable.get()));
60+
});
61+
5162
});
5263

5364
}

0 commit comments

Comments
 (0)