Skip to content

Commit

Permalink
Merge pull request #118 from ashleyfrieze/VariablesNotThreadLocal
Browse files Browse the repository at this point in the history
Removed thread-segregation from `Variable` and `let`.
  • Loading branch information
greghaskins committed Aug 30, 2017
2 parents 3fb6960 + d506ccd commit b7b920a
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/main/java/com/greghaskins/spectrum/Variable.java
Expand Up @@ -10,7 +10,7 @@
*/
public final class Variable<T> implements Supplier<T> {

private ThreadLocal<T> value = new ThreadLocal<>();
private T value;

/**
* Create a Variable with a {@code null} initial value.
Expand All @@ -33,7 +33,7 @@ public Variable(final T value) {
*/
@Override
public T get() {
return this.value.get();
return this.value;
}

/**
Expand All @@ -42,6 +42,6 @@ public T get() {
* @param value new value
*/
public void set(final T value) {
this.value.set(value);
this.value = value;
}
}
18 changes: 18 additions & 0 deletions src/test/java/specs/LetSpecs.java
Expand Up @@ -182,8 +182,26 @@ public class LetSpecs {
assertThat(result.getFailures().get(1).getMessage(), is("Bong!"));
});
});
});

describe("let across multiple threads", () -> {
final Supplier<List<String>> 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));
});
});
});
}
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/specs/VariableSpecs.java
Expand Up @@ -48,6 +48,17 @@ public class VariableSpecs {
assertNull(name.get());
});

it("has the same value across threads", () -> {
final Variable<String> outerVariable = new Variable<>("outer");
final Variable<String> whatWorkerThreadSees = new Variable<>();

Thread worker = new Thread(() -> whatWorkerThreadSees.set(outerVariable.get()));
worker.start();
worker.join();

assertThat(whatWorkerThreadSees.get(), is(outerVariable.get()));
});

});

}
Expand Down

0 comments on commit b7b920a

Please sign in to comment.