File tree Expand file tree Collapse file tree 3 files changed +32
-3
lines changed
main/java/com/greghaskins/spectrum Expand file tree Collapse file tree 3 files changed +32
-3
lines changed Original file line number Diff line number Diff line change 10
10
*/
11
11
public final class Variable <T > implements Supplier <T > {
12
12
13
- private ThreadLocal < T > value = new ThreadLocal <>() ;
13
+ private T value ;
14
14
15
15
/**
16
16
* Create a Variable with a {@code null} initial value.
@@ -33,7 +33,7 @@ public Variable(final T value) {
33
33
*/
34
34
@ Override
35
35
public T get () {
36
- return this .value . get () ;
36
+ return this .value ;
37
37
}
38
38
39
39
/**
@@ -42,6 +42,6 @@ public T get() {
42
42
* @param value new value
43
43
*/
44
44
public void set (final T value ) {
45
- this .value . set ( value ) ;
45
+ this .value = value ;
46
46
}
47
47
}
Original file line number Diff line number Diff line change @@ -182,8 +182,26 @@ public class LetSpecs {
182
182
assertThat (result .getFailures ().get (1 ).getMessage (), is ("Bong!" ));
183
183
});
184
184
});
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" );
185
192
193
+ // used as a box for the integer
194
+ AtomicInteger atomicInteger = new AtomicInteger ();
186
195
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
+ });
187
205
});
188
206
});
189
207
}
Original file line number Diff line number Diff line change @@ -48,6 +48,17 @@ public class VariableSpecs {
48
48
assertNull (name .get ());
49
49
});
50
50
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
+
51
62
});
52
63
53
64
}
You can’t perform that action at this time.
0 commit comments