FIx race condition in LazyOptional (#7611)

This commit is contained in:
malte0811 authored and GitHub committed 2021-02-15 12:11:27 -08:00
1 parent 007cd42ec6
commit a89ce2d6f1
2 files changed
+82 -16

No files matched your search

@@ -23,12 +23,13 @@ import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -57,7 +58,11 @@ import net.minecraftforge.common.capabilities.Capability;
public class LazyOptional<T>
{
private final NonNullSupplier<T> supplier;
private AtomicReference<T> resolved;
private final Object lock = new Object();
// null -> not resolved yet
// non-null and contains non-null value -> resolved
// non-null and contains null -> resolved, but supplier returned null (contract violation)
private Mutable<T> resolved;
private Set<NonNullConsumer<LazyOptional<T>>> listeners = new HashSet<>();
private boolean isValid = true;
@@ -105,26 +110,25 @@ public class LazyOptional<T>
private @Nullable T getValue()
{
if (!isValid)
if (!isValid || supplier == null)
return null;
if (resolved != null)
return resolved.get();
if (supplier != null)
if (resolved == null)
{
resolved = new AtomicReference<>(null);
T temp = supplier.get();
if (temp == null)
synchronized (lock)
{
LOGGER.catching(Level.WARN, new NullPointerException("Supplier should not return null value"));
return null;
// resolved == null: Double checked locking to prevent two threads from resolving
if (resolved == null)
{
T temp = supplier.get();
if (temp == null)
LOGGER.catching(Level.WARN, new NullPointerException("Supplier should not return null value"));
resolved = new MutableObject<>(temp);
}
}
resolved.set(temp);
return resolved.get();
}
return null;
return resolved.getValue();
}
private T getValueUnsafe()
{
T ret = getValue();