fix(storage): make computeIfAbsent atomic (#1699)

This commit is contained in:
Jason van Zyl authored and GitHub committed 2026-07-05 09:32:43 -05:00
1 parent f8e8984c16
commit 71ee94d8b0
2 files changed
+89

No files matched your search

@@ -3,6 +3,13 @@ package io.github.hectorvent.floci.core.storage;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -59,6 +66,46 @@ class StorageBackedMapTest
assertFalse(storage.get("alpha").isPresent());
}
@Test
void computeIfAbsentCreatesOneValueUnderConcurrentAccess()
throws Exception
{
InMemoryStorage<String, Map<String, String>> storage = new InMemoryStorage<>();
StorageBackedMap<Map<String, String>> map = new StorageBackedMap<>(storage);
AtomicInteger calls = new AtomicInteger();
CountDownLatch firstMappingEntered = new CountDownLatch(1);
CountDownLatch releaseFirstMapping = new CountDownLatch(1);
CountDownLatch secondCallStarted = new CountDownLatch(1);
try (var executor = Executors.newFixedThreadPool(2)) {
var first = executor.submit(() -> map.computeIfAbsent("us-west-2", key -> {
calls.incrementAndGet();
firstMappingEntered.countDown();
await(releaseFirstMapping);
return Map.of("first", "one");
}));
await(firstMappingEntered);
var second = executor.submit(() -> {
secondCallStarted.countDown();
return map.computeIfAbsent("us-west-2", key -> {
calls.incrementAndGet();
return Map.of("second", "two");
});
});
await(secondCallStarted);
assertTimesOut(second);
releaseFirstMapping.countDown();
Map<String, String> firstValue = first.get(5, TimeUnit.SECONDS);
Map<String, String> secondValue = second.get(5, TimeUnit.SECONDS);
assertEquals(1, calls.get());
assertEquals(firstValue, secondValue);
assertEquals(firstValue, storage.get("us-west-2").orElseThrow());
}
}
@Test
void conditionalReplaceOnlyUpdatesMatchingValues()
{
@@ -102,4 +149,27 @@ class StorageBackedMapTest
assertFalse(storage.get("alpha").isPresent());
assertTrue(map.isEmpty());
}
private static void await(CountDownLatch latch)
{
try {
assertTrue(latch.await(5, TimeUnit.SECONDS));
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
private static void assertTimesOut(Future<?> future)
throws InterruptedException, ExecutionException
{
try {
future.get(250, TimeUnit.MILLISECONDS);
}
catch (TimeoutException expected) {
return;
}
throw new AssertionError("future completed before the first mapping function was released");
}
}