diff --git a/vavr/src/main/java/io/vavr/Lazy.java b/vavr/src/main/java/io/vavr/Lazy.java index 64c097c71..a4993b963 100644 --- a/vavr/src/main/java/io/vavr/Lazy.java +++ b/vavr/src/main/java/io/vavr/Lazy.java @@ -30,6 +30,7 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; import java.util.Objects; +import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; @@ -60,6 +61,7 @@ public final class Lazy implements Value, Supplier, Serializable { private static final long serialVersionUID = 1L; + private final ReentrantLock lock = new ReentrantLock(); // read http://javarevisited.blogspot.de/2014/05/double-checked-locking-on-singleton-in-java.html private transient volatile Supplier supplier; @@ -155,11 +157,16 @@ public T get() { return (supplier == null) ? value : computeValue(); } - private synchronized T computeValue() { - final Supplier s = supplier; - if (s != null) { - value = s.get(); - supplier = null; + private T computeValue() { + lock.lock(); + try { + final Supplier s = supplier; + if (s != null) { + value = s.get(); + supplier = null; + } + } finally { + lock.unlock(); } return value; }