Delete the transitional runtime lookups and weak engine holders

- Delete LazyBoundedCache, its test and the gate check for it
- Delete PackRuntime.forContext and pass explicit runtimes in generator sampling tests
- Hold structure placement scope indexes per live engine and drop them in the shutdown sequence
- Hold the ownership store engine strongly now that closed engines release their store
This commit is contained in:
piexel committed 2026-11-26 21:35:16 +01:00
1 parent 7a3d2b10bb
commit e0ad0b3ea9
14 files changed
+69 -262

No files matched your search

@@ -1,49 +0,0 @@
package art.arcane.iris.generation.cache;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.function.Function;
public final class LazyBoundedCache<K, V> {
private final int maximumSize;
private transient LinkedHashMap<K, V> entries;
public LazyBoundedCache(int maximumSize) {
if (maximumSize <= 0) {
throw new IllegalArgumentException("Maximum cache size must be positive");
}
this.maximumSize = maximumSize;
}
public synchronized V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
K requiredKey = Objects.requireNonNull(key, "Cache key");
Function<? super K, ? extends V> requiredMapping = Objects.requireNonNull(mappingFunction, "Cache mapping function");
if (entries != null) {
V cached = entries.get(requiredKey);
if (cached != null) {
return cached;
}
}
V computed = requiredMapping.apply(requiredKey);
if (computed == null) {
return null;
}
if (entries == null) {
entries = new LinkedHashMap<>(maximumSize, 1F, true);
}
entries.put(requiredKey, computed);
if (entries.size() > maximumSize) {
entries.sequencedKeySet().removeFirst();
}
return computed;
}
synchronized boolean isInitialized() {
return entries != null;
}
synchronized int size() {
return entries == null ? 0 : entries.size();
}
}
@@ -20,6 +20,7 @@ package art.arcane.iris.generation.runtime;
import art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.structure.placement.StructurePlacementScope;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.EngineBackgroundTasks.BackgroundTaskDrain;
@@ -215,6 +216,7 @@ final class EngineShutdownSequence {
private void releaseStructureRegistries() {
NativeStructureOwnershipStore.release(engine);
IrisStructureLocator.invalidate(engine);
StructurePlacementScope.invalidate(engine);
StructureReachability.invalidate(engine);
NativeStructureVolumeIndex.uninstall(engine);
}
@@ -137,14 +137,6 @@ public final class PackRuntime {
return of(engine, engine.getData());
}
/**
* The scope for a pack object whose class still finds its engine through the pack data's context. Each use is a
* caller that has not been handed its runtime scope yet.
*/
public static PackRuntime forContext(IrisData data) {
return of(data == null ? null : data.getEngine(), data);
}
/** The owning engine, or null for an engine-less scope. */
public Engine engine() {
return engine;
@@ -13,7 +13,6 @@ import art.arcane.volmlib.util.matter.MatterSlice;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
@@ -88,7 +87,6 @@ public final class NativeStructureOwnershipStore {
}
static final class State {
private final WeakReference<Engine> engine;
private final Storage storage;
private final Cache<NativeStructureOwnershipRecord.OwnershipKey, Authority> authorities;
private final ReentrantReadWriteLock lifecycleLock;
@@ -100,8 +98,7 @@ public final class NativeStructureOwnershipStore {
}
State(Engine engine, Storage storage) {
this.engine = new WeakReference<>(Objects.requireNonNull(engine,
"Native structure ownership store requires an engine"));
Objects.requireNonNull(engine, "Native structure ownership store requires an engine");
this.storage = Objects.requireNonNull(storage,
"Native structure ownership storage must not be null");
this.authorities = Caffeine.newBuilder().maximumSize(MAX_CACHED_AUTHORITIES).build();
@@ -226,19 +223,10 @@ public final class NativeStructureOwnershipStore {
}
private void requireOpen() {
engine();
if (closed) {
throw new GenerationClosedException("Native structure ownership store is closed");
}
}
private Engine engine() {
Engine active = engine.get();
if (active == null) {
throw new IllegalStateException("Native structure ownership engine is unavailable");
}
return active;
}
}
interface Storage {
@@ -255,18 +243,18 @@ public final class NativeStructureOwnershipStore {
}
static final class MantleStorage implements Storage {
private final WeakReference<Engine> engine;
private final Engine engine;
private final Map<PendingTarget, NativeStructureOwnershipBundle> pendingBundles;
private final WeakReference<IrisEngine> retirementEngine;
private final IrisEngine retirementEngine;
private final IntConsumer retirementListener;
MantleStorage(Engine engine) {
Engine required = Objects.requireNonNull(engine,
"Native structure ownership store requires an engine");
this.engine = new WeakReference<>(required);
this.engine = required;
this.pendingBundles = new ConcurrentHashMap<>();
if (required instanceof IrisEngine irisEngine) {
this.retirementEngine = new WeakReference<>(irisEngine);
this.retirementEngine = irisEngine;
this.retirementListener = this::flushRuntime;
irisEngine.addGenerationRuntimeRetirementListener(retirementListener);
} else {
@@ -350,7 +338,7 @@ public final class NativeStructureOwnershipStore {
@Override
public void close() {
IrisEngine activeRetirementEngine = retirementEngine == null ? null : retirementEngine.get();
IrisEngine activeRetirementEngine = retirementEngine;
if (activeRetirementEngine != null) {
activeRetirementEngine.removeGenerationRuntimeRetirementListener(retirementListener);
}
@@ -425,10 +413,7 @@ public final class NativeStructureOwnershipStore {
}
private RuntimeMantleOwner owner() {
Engine active = engine.get();
if (active == null) {
throw new IllegalStateException("Native structure ownership engine is unavailable");
}
Engine active = engine;
EngineMantle mantle = active.getMantle();
int runtimeId = active.getCacheID();
if (!(active instanceof IrisEngine irisEngine)) {
@@ -7,16 +7,16 @@ import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.volmlib.util.collection.KList;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public final class StructurePlacementScope {
private static final List<CachedScopeIndex> SCOPE_INDEXES = new ArrayList<>();
/** Scope indexes of live engines; each engine invalidates its own entry when it closes. */
private static final Map<Engine, CachedScopeIndex> SCOPE_INDEXES = new IdentityHashMap<>();
private StructurePlacementScope() {
}
@@ -63,26 +63,30 @@ public final class StructurePlacementScope {
return false;
}
public static void invalidate(Engine engine) {
synchronized (SCOPE_INDEXES) {
SCOPE_INDEXES.remove(engine);
}
}
static boolean isIndexed(Engine engine) {
synchronized (SCOPE_INDEXES) {
return SCOPE_INDEXES.containsKey(engine);
}
}
private static ScopeIndex scopeIndex(Engine engine) {
if (engine.isClosed()) {
return buildScopeIndex(engine);
}
int revision = engine.getCacheID();
synchronized (SCOPE_INDEXES) {
for (int i = SCOPE_INDEXES.size() - 1; i >= 0; i--) {
CachedScopeIndex cached = SCOPE_INDEXES.get(i);
Engine indexedEngine = cached.engine().get();
if (indexedEngine == null) {
SCOPE_INDEXES.remove(i);
continue;
}
if (indexedEngine == engine) {
if (cached.revision() == revision) {
return cached.index();
}
SCOPE_INDEXES.remove(i);
break;
}
CachedScopeIndex cached = SCOPE_INDEXES.get(engine);
if (cached != null && cached.revision() == revision) {
return cached.index();
}
ScopeIndex index = buildScopeIndex(engine);
SCOPE_INDEXES.add(new CachedScopeIndex(new WeakReference<>(engine), revision, index));
SCOPE_INDEXES.put(engine, new CachedScopeIndex(revision, index));
return index;
}
}
@@ -155,7 +159,7 @@ public final class StructurePlacementScope {
}
}
private record CachedScopeIndex(WeakReference<Engine> engine, int revision, ScopeIndex index) {
private record CachedScopeIndex(int revision, ScopeIndex index) {
}
private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) {
@@ -39,7 +39,7 @@ public class IrisBiomeChildrenGeneratorTest {
}
private double[] sampleSharedChildStyleGenerator(IrisGeneratorStyle childStyle) {
return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), packData);
return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), PackRuntime.of(packData.getEngine(), packData));
}
private static RNG deriveSharedChildStyleSeed() {
@@ -1,139 +0,0 @@
package art.arcane.iris.generation.cache;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class LazyBoundedCacheTest {
@Test
public void backingStorageIsLazy() {
LazyBoundedCache<String, Object> cache = new LazyBoundedCache<>(8);
assertFalse(cache.isInitialized());
assertEquals(0, cache.size());
assertNull(cache.computeIfAbsent("missing", ignored -> null));
assertFalse(cache.isInitialized());
Object expected = new Object();
assertSame(expected, cache.computeIfAbsent("present", ignored -> expected));
assertTrue(cache.isInitialized());
assertEquals(1, cache.size());
}
@Test
public void capacityUsesAccessOrder() {
LazyBoundedCache<Integer, Object> cache = new LazyBoundedCache<>(8);
Object first = new Object();
cache.computeIfAbsent(0, ignored -> first);
for (int key = 1; key < 8; key++) {
cache.computeIfAbsent(key, ignored -> new Object());
}
assertSame(first, cache.computeIfAbsent(0, ignored -> new Object()));
cache.computeIfAbsent(8, ignored -> new Object());
AtomicInteger reloads = new AtomicInteger();
cache.computeIfAbsent(1, ignored -> {
reloads.incrementAndGet();
return new Object();
});
assertEquals(1, reloads.get());
assertEquals(8, cache.size());
assertSame(first, cache.computeIfAbsent(0, ignored -> new Object()));
}
@Test
public void concurrentSameKeyComputesOnce() throws Exception {
int threadCount = 16;
LazyBoundedCache<String, Object> cache = new LazyBoundedCache<>(8);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch resolverEntered = new CountDownLatch(1);
CountDownLatch releaseResolver = new CountDownLatch(1);
AtomicInteger computations = new AtomicInteger();
Object expected = new Object();
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
List<Future<Object>> futures = new ArrayList<>(threadCount);
try {
for (int index = 0; index < threadCount; index++) {
futures.add(executor.submit(() -> {
start.await();
return cache.computeIfAbsent("shared", ignored -> {
computations.incrementAndGet();
resolverEntered.countDown();
await(releaseResolver);
return expected;
});
}));
}
start.countDown();
assertTrue(resolverEntered.await(5L, TimeUnit.SECONDS));
releaseResolver.countDown();
for (Future<Object> future : futures) {
assertSame(expected, future.get(5L, TimeUnit.SECONDS));
}
} finally {
releaseResolver.countDown();
executor.shutdownNow();
assertTrue(executor.awaitTermination(5L, TimeUnit.SECONDS));
}
assertEquals(1, computations.get());
assertEquals(1, cache.size());
}
@Test
public void keysRetainIdentityEqualitySemantics() {
Object firstIdentity = new String("same");
Object secondIdentity = new String("same");
LazyBoundedCache<IdentityKey, Object> cache = new LazyBoundedCache<>(8);
Object firstValue = new Object();
assertSame(firstValue, cache.computeIfAbsent(new IdentityKey(firstIdentity), ignored -> firstValue));
assertSame(firstValue, cache.computeIfAbsent(new IdentityKey(firstIdentity), ignored -> new Object()));
assertNotSame(firstValue, cache.computeIfAbsent(new IdentityKey(secondIdentity), ignored -> new Object()));
assertEquals(2, cache.size());
}
private static void await(CountDownLatch latch) {
try {
if (!latch.await(5L, TimeUnit.SECONDS)) {
throw new IllegalStateException("Timed out waiting for cache test latch");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
}
private static final class IdentityKey {
private final Object identity;
private IdentityKey(Object identity) {
this.identity = identity;
}
@Override
public boolean equals(Object other) {
return other instanceof IdentityKey key && identity == key.identity;
}
@Override
public int hashCode() {
return System.identityHashCode(identity);
}
}
}
@@ -36,7 +36,7 @@ public class IrisDecoratorVarianceGeneratorTest {
}
private double[] sampleSharedVarianceStyleGenerator(IrisGeneratorStyle varianceStyle) {
return sampleSharedGenerator(varianceStyle, decorator.deriveVarianceSeed(new RNG(WORLD_SEED), packData), packData);
return sampleSharedGenerator(varianceStyle, decorator.deriveVarianceSeed(new RNG(WORLD_SEED), packData), PackRuntime.of(packData.getEngine(), packData));
}
private static IrisDecorator createDecoratorWithZoomedSimplexVariance() {
@@ -2,6 +2,7 @@ package art.arcane.iris.generation.runtime;
import art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.structure.placement.StructurePlacementScope;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.EngineRuntimeBuilder.RuntimeAssembly;
@@ -144,6 +145,7 @@ public class EngineShutdownDrainTest {
try (MockedStatic<NativeStructureOwnershipStore> ownership = mockStatic(NativeStructureOwnershipStore.class);
MockedStatic<IrisStructureLocator> locator = mockStatic(IrisStructureLocator.class);
MockedStatic<StructureReachability> reachability = mockStatic(StructureReachability.class);
MockedStatic<StructurePlacementScope> scopes = mockStatic(StructurePlacementScope.class);
MockedStatic<NativeStructureVolumeIndex> volumes = mockStatic(NativeStructureVolumeIndex.class)) {
fixture.shutdown.close();
@@ -151,6 +153,7 @@ public class EngineShutdownDrainTest {
ownership.verify(() -> NativeStructureOwnershipStore.release(fixture.engine));
locator.verify(() -> IrisStructureLocator.invalidate(fixture.engine));
reachability.verify(() -> StructureReachability.invalidate(fixture.engine));
scopes.verify(() -> StructurePlacementScope.invalidate(fixture.engine));
volumes.verify(() -> NativeStructureVolumeIndex.uninstall(fixture.engine));
}
}
@@ -92,11 +92,11 @@ public class ContinentGeneratorTest {
}
private double[] sampleSharedStyleGenerator(IrisGeneratorStyle style) {
return sampleSharedGenerator(style, ContinentGenerator.deriveContinentSeed(new RNG(WORLD_SEED)), packData);
return sampleSharedGenerator(style, ContinentGenerator.deriveContinentSeed(new RNG(WORLD_SEED)), PackRuntime.of(packData.getEngine(), packData));
}
private double[] sampleContinentMap(IrisDimension dimension, double[][] blocks) {
return sampleAtBlocks(ContinentGenerator.create(dimension, new RNG(WORLD_SEED), PackRuntime.forContext(packData)), blocks);
return sampleAtBlocks(ContinentGenerator.create(dimension, new RNG(WORLD_SEED), PackRuntime.of(packData.getEngine(), packData)), blocks);
}
private static double[][] shrinkByContinentZoom(double[][] blocks) {
@@ -35,7 +35,7 @@ public class IrisDimensionCarvingEntryTest {
}
private double[] sampleSharedChildStyleGenerator(IrisGeneratorStyle childStyle) {
return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), packData);
return sampleSharedGenerator(childStyle, deriveSharedChildStyleSeed(), PackRuntime.of(packData.getEngine(), packData));
}
private RNG deriveSharedChildStyleSeed() {
@@ -54,7 +54,6 @@ public class PackRuntimeStateGateTest {
"Lart/arcane/iris/world/IrisWorld;",
"Lart/arcane/volmlib/nativelib/terrain/NativeWorld;",
"Lorg/bukkit/World;");
private static final String LAZY_BOUNDED_CACHE = "Lart/arcane/iris/generation/cache/LazyBoundedCache;";
private static final Pattern REFERENCED_TYPE = Pattern.compile("L(art/arcane/iris/[A-Za-z0-9_/$]+)[;<]");
enum Kind {
@@ -276,22 +275,6 @@ public class PackRuntimeStateGateTest {
}
}
@Test
public void packTypesDoNotUseLazyBoundedCache() throws Exception {
PackTypes types = PackTypes.scan();
List<String> failures = new ArrayList<>();
for (String type : types.packTypesWithNested()) {
for (ClassFileFacts.DeclaredField field : types.facts(type).fields()) {
if (mentions(field, LAZY_BOUNDED_CACHE)) {
failures.add(type + "#" + field.name());
}
}
}
if (!failures.isEmpty()) {
fail("Pack types must not cache derived values; build them in a runtime object:" + join(failures));
}
}
@Test
public void scanFindsThePackTypes() throws Exception {
PackTypes types = PackTypes.scan();
@@ -363,6 +346,7 @@ public class PackRuntimeStateGateTest {
holder("art.arcane.iris.structure.nativegen.NativeStructureVolumeIndex", "INDEXES", Kind.STATIC, "live-engine registry; a closed engine uninstalls its index in the shutdown sequence (EngineShutdownDrainTest)"),
holder("art.arcane.iris.structure.placement.IrisStructureLocator", "INDEX_CACHE", Kind.STATIC, "live-engine registry; a closed engine invalidates its index in the shutdown sequence (EngineShutdownDrainTest)"),
holder("art.arcane.iris.structure.placement.IrisStructureLocator", "LOCATABLE_INDEX_CACHE", Kind.STATIC, "live-engine registry; a closed engine invalidates its index in the shutdown sequence (EngineShutdownDrainTest)"),
holder("art.arcane.iris.structure.placement.StructurePlacementScope", "SCOPE_INDEXES", Kind.STATIC, "live-engine registry; a closed engine invalidates its index in the shutdown sequence (EngineShutdownDrainTest)"),
holder("art.arcane.iris.structure.placement.StructureReachability", "REACHABLE_CACHE", Kind.STATIC, "live-engine registry; a closed engine invalidates its keys in the shutdown sequence (EngineShutdownDrainTest)"),
holder("art.arcane.iris.generation.runtime.EngineTickRegistry", "TICK_ENGINES", Kind.STATIC, "live-engine registry; every engine unregisters itself when it closes (EngineReleaseProbeTest)"),
holder("art.arcane.iris.pack.loading.IrisData", "ENGINE_HOLDERS", Kind.STATIC, "pack data with live engines; an engine unregisters from its pack data when it closes (EngineReleaseProbeTest)"),
@@ -1,5 +1,6 @@
package art.arcane.iris.structure.placement;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
@@ -19,6 +20,31 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class StructurePlacementScopeTest {
@Test
public void scopeIndexIsHeldOnlyUntilTheEngineInvalidatesIt() {
Engine liveEngine = engineWithoutStructures();
Engine closedEngine = engineWithoutStructures();
when(closedEngine.isClosed()).thenReturn(true);
StructurePlacementScope.placementsAt(liveEngine, 0, 0);
StructurePlacementScope.placementsAt(closedEngine, 0, 0);
assertTrue(StructurePlacementScope.isIndexed(liveEngine));
assertFalse(StructurePlacementScope.isIndexed(closedEngine));
StructurePlacementScope.invalidate(liveEngine);
assertFalse(StructurePlacementScope.isIndexed(liveEngine));
}
private static Engine engineWithoutStructures() {
Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS);
IrisDimension dimension = mock(IrisDimension.class);
when(engine.getDimension()).thenReturn(dimension);
when(engine.getAllBiomes()).thenReturn(new KList<>());
when(dimension.getStructures()).thenReturn(new KList<>());
when(dimension.getAllRegions(engine)).thenReturn(new KList<>());
return engine;
}
@Test
public void caveBiomeContributesOnlyCaveAnchoredPlacements() {
IrisStructurePlacement surfacePlacement = new IrisStructurePlacement();
@@ -2,7 +2,6 @@ package art.arcane.iris.testsupport;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.volmlib.util.math.RNG;
import art.arcane.volmlib.util.noise.CNG;
@@ -14,8 +13,8 @@ public final class GeneratorSampling {
private GeneratorSampling() {
}
public static double[] sampleSharedGenerator(IrisGeneratorStyle style, RNG seed, IrisData packData) {
return sampleAtBlocks(style.create(seed, PackRuntime.forContext(packData)), SAMPLE_BLOCKS);
public static double[] sampleSharedGenerator(IrisGeneratorStyle style, RNG seed, PackRuntime runtime) {
return sampleAtBlocks(style.create(seed, runtime), SAMPLE_BLOCKS);
}
public static double[] sampleAtBlocks(CNG generator, double[][] blocks) {