Skip to content

Commit 3b8171e

Browse files
further improvement of Lazy.get()
1 parent 63e7872 commit 3b8171e

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

javaslang/src/main/java/javaslang/Lazy.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,9 @@ public final class Lazy<T> implements Value<T>, Supplier<T>, Serializable {
4444

4545
// read http://javarevisited.blogspot.de/2014/05/double-checked-locking-on-singleton-in-java.html
4646
private transient volatile Supplier<? extends T> supplier;
47-
private volatile T value;
47+
48+
// does not need to be volatile, visibility piggy-backs on volatile read of `supplier`
49+
private T value;
4850

4951
// should not be called directly
5052
private Lazy(Supplier<? extends T> supplier) {
@@ -133,12 +135,13 @@ public Option<T> filter(Predicate<? super T> predicate) {
133135
*/
134136
@Override
135137
public T get() {
138+
// using a local var speeds up the double-check idiom by 25%, see Effective Java, Item 71
136139
Supplier<? extends T> tmp = supplier;
137140
if (tmp != null) {
138141
synchronized (this) {
139142
tmp = supplier;
140143
if (tmp != null) {
141-
value = supplier.get();
144+
value = tmp.get();
142145
supplier = null; // free mem
143146
}
144147
}

0 commit comments

Comments
 (0)