mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-18 19:39:22 +00:00
FIx race condition in LazyOptional (#7611)
This commit is contained in:
1 parent
007cd42ec6
commit
a89ce2d6f1
2 files changed
+82
-16
No files matched your search
@@ -0,0 +1,62 @@
|
||||
package net.minecraftforge.test;
|
||||
|
||||
import com.mojang.datafixers.util.Unit;
|
||||
import net.minecraftforge.common.util.LazyOptional;
|
||||
import org.apache.commons.lang3.mutable.MutableInt;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class LazyOptionalTest
|
||||
{
|
||||
@Test
|
||||
public void testConcurrentResolve() throws InterruptedException {
|
||||
AtomicInteger supplierCalls = new AtomicInteger();
|
||||
LazyOptional<Unit> slowLazy = LazyOptional.of(() -> {
|
||||
supplierCalls.incrementAndGet();
|
||||
try
|
||||
{
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
catch(InterruptedException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
return Unit.INSTANCE;
|
||||
});
|
||||
List<Thread> threads = new ArrayList<>();
|
||||
AtomicInteger successfulThreads = new AtomicInteger();
|
||||
for (int i = 0; i < 2; ++i)
|
||||
{
|
||||
threads.add(new Thread(() -> {
|
||||
// Resolve uses getValueUnsafe, so it throws if the value is unexpectedly absent
|
||||
if (slowLazy.resolve().isPresent()) {
|
||||
successfulThreads.incrementAndGet();
|
||||
}
|
||||
}));
|
||||
}
|
||||
threads.forEach(Thread::start);
|
||||
for (Thread thread : threads)
|
||||
{
|
||||
thread.join();
|
||||
}
|
||||
assertEquals(threads.size(), successfulThreads.get());
|
||||
assertEquals(1, supplierCalls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidSupplier() {
|
||||
MutableInt supplierCalls = new MutableInt();
|
||||
LazyOptional<Unit> badLazy = LazyOptional.of(() -> {
|
||||
supplierCalls.increment();
|
||||
return null;
|
||||
});
|
||||
badLazy.ifPresent(u -> {});
|
||||
badLazy.ifPresent(u -> {});
|
||||
assertEquals(1, supplierCalls.intValue());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user