From 3b8171ed9e42fb748808c2652eaea008598d3d77 Mon Sep 17 00:00:00 2001 From: Daniel Dietrich Date: Sat, 17 Sep 2016 13:29:44 +0200 Subject: [PATCH] further improvement of Lazy.get() --- javaslang/src/main/java/javaslang/Lazy.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/javaslang/src/main/java/javaslang/Lazy.java b/javaslang/src/main/java/javaslang/Lazy.java index 77c515e373..322f1ca7c3 100644 --- a/javaslang/src/main/java/javaslang/Lazy.java +++ b/javaslang/src/main/java/javaslang/Lazy.java @@ -44,7 +44,9 @@ public final class Lazy implements Value, Supplier, Serializable { // read http://javarevisited.blogspot.de/2014/05/double-checked-locking-on-singleton-in-java.html private transient volatile Supplier 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 supplier) { @@ -133,12 +135,13 @@ public Option filter(Predicate predicate) { */ @Override public T get() { + // using a local var speeds up the double-check idiom by 25%, see Effective Java, Item 71 Supplier tmp = supplier; if (tmp != null) { synchronized (this) { tmp = supplier; if (tmp != null) { - value = supplier.get(); + value = tmp.get(); supplier = null; // free mem } }