Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace synchronized method/block with reentrant lock (#2842) #2845

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions vavr/src/main/java/io/vavr/Lazy.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -60,6 +61,7 @@
public final class Lazy<T> implements Value<T>, Supplier<T>, 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<? extends T> supplier;
Expand Down Expand Up @@ -155,11 +157,16 @@ public T get() {
return (supplier == null) ? value : computeValue();
}

private synchronized T computeValue() {
final Supplier<? extends T> s = supplier;
if (s != null) {
value = s.get();
supplier = null;
private T computeValue() {
lock.lock();
try {
final Supplier<? extends T> s = supplier;
if (s != null) {
value = s.get();
supplier = null;
}
} finally {
lock.unlock();
}
return value;
}
Expand Down