Skip to content

Commit

Permalink
further improvement of Lazy.get()
Browse files Browse the repository at this point in the history
  • Loading branch information
danieldietrich committed Sep 17, 2016
1 parent 63e7872 commit 3b8171e
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions javaslang/src/main/java/javaslang/Lazy.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ public final class Lazy<T> implements Value<T>, Supplier<T>, Serializable {

// read http://javarevisited.blogspot.de/2014/05/double-checked-locking-on-singleton-in-java.html
private transient volatile Supplier<? extends T> supplier;
private volatile T value;

// does not need to be volatile, visibility piggy-backs on volatile read of `supplier`
private T value;

// should not be called directly
private Lazy(Supplier<? extends T> supplier) {
Expand Down Expand Up @@ -133,12 +135,13 @@ public Option<T> filter(Predicate<? super T> predicate) {
*/
@Override
public T get() {
// using a local var speeds up the double-check idiom by 25%, see Effective Java, Item 71
Supplier<? extends T> tmp = supplier;
if (tmp != null) {
synchronized (this) {
tmp = supplier;
if (tmp != null) {
value = supplier.get();
value = tmp.get();
supplier = null; // free mem
}
}
Expand Down

0 comments on commit 3b8171e

Please sign in to comment.