Move per-thread generation state into engine-owned thread slots

- Keep live threads in thread slots and add bound values that a thread sets and removes
- Keep engine thread frames in thread slots instead of a thread-local overflow
- Move bake, hydrology, carver, mantle writer, complex, subterrain, terrain and history thread-locals into thread slots
- Keep the carving resolver fallback state in the pack runtime instead of a static thread-local
- Check that a live worker drops the resolver state and engine once the engine is unreachable
This commit is contained in:
piexel committed 2026-11-26 20:37:00 +01:00
1 parent 99a6e5ddb6
commit d6d87a47d2
24 files changed
+200 -127

No files matched your search

@@ -1,5 +1,6 @@
package art.arcane.iris.generation.bake;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.cache.ConcurrentClockCache;
import art.arcane.iris.generation.stream.ProvisionalSampling;
@@ -16,7 +17,7 @@ public final class ChunkBakeCache {
private final PlaneSource source;
private final ConcurrentClockCache<ChunkPlanes> entries;
private final ThreadLocal<Recent> recent = ThreadLocal.withInitial(Recent::new);
private final ThreadSlots<Recent> recent = new ThreadSlots<>(Recent::new);
private volatile int generation;
public ChunkBakeCache(PlaneSource source, int capacityChunks) {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.hydrology.engine;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.runtime.HydrologyPlanException;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.concurrent.MultiBurst;
@@ -78,7 +79,7 @@ public final class HydrologyRuntime {
private final NaturalHeights naturalHeight;
private final BooleanSupplier mainThread;
private final RasterLru rasters;
private final ThreadLocal<LastRaster> last;
private final ThreadSlots<LastRaster> last;
private final Set<Long> queued;
private final ConcurrentHashMap<Long, CompletableFuture<ChunkWaterRaster>> building;
private final RasterFailures failures;
@@ -132,7 +133,7 @@ public final class HydrologyRuntime {
this.naturalHeight = Objects.requireNonNull(naturalHeight, "naturalHeight");
this.mainThread = Objects.requireNonNull(mainThread, "mainThread");
this.rasters = new RasterLru();
this.last = ThreadLocal.withInitial(LastRaster::new);
this.last = new ThreadSlots<>(LastRaster::new);
this.queued = ConcurrentHashMap.newKeySet();
this.building = new ConcurrentHashMap<>();
this.failures = new RasterFailures(ticker);
@@ -18,6 +18,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
@@ -111,7 +112,7 @@ public class IrisCaveCarver3D {
private final int worldMinimumY;
private final int densityMaximumY;
private final ThreadLocal<Boolean> carving = ThreadLocal.withInitial(() -> false);
private final ThreadLocal<CaveCarveScratch> scratchCache = ThreadLocal.withInitial(CaveCarveScratch::new);
private final ThreadSlots<CaveCarveScratch> scratchCache = new ThreadSlots<>(CaveCarveScratch::new);
private final CaveDensityGrid densityGrid;
private final CaveDensityGrid.Owner densityOwner;
private final CaveDensityGrid.Owner warpOwner;
@@ -19,6 +19,7 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.spi.IrisLogging;
import art.arcane.iris.structure.object.ObjectWaterRule;
import art.arcane.iris.world.storage.matter.TileWrapper;
@@ -86,12 +87,12 @@ public class MantleWriter implements ObjectPassPlacer, AutoCloseable {
@ToString.Exclude
private final ThreadLocal<Integer> activeComponentPriority = new ThreadLocal<>();
@Getter(AccessLevel.NONE)
private final ThreadLocal<ObjectPlacementCapture> objectPlacementCapture = new ThreadLocal<>();
private final ThreadSlots<ObjectPlacementCapture> objectPlacementCapture = ThreadSlots.bindings();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@ToString.Exclude
private final ThreadLocal<ObjectWater> objectWater = new ThreadLocal<>();
private final ThreadSlots<ObjectWater> objectWater = ThreadSlots.bindings();
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
@@ -23,29 +23,17 @@ import art.arcane.iris.generation.runtime.IrisEngine.BiomeEnvironmentBinding;
import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeBinding;
import art.arcane.iris.generation.runtime.IrisEngine.GenerationRuntimeScope;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
/**
* Every per-thread engine binding (runtime assembly, biome environment, generation runtime scope) in one frame.
* The engine getters run on generation hot paths, where a ThreadLocal lookup probes long collision chains in the
* workers' crowded thread-local maps. Frames therefore live in a table indexed by thread id and owned by their
* thread; a frame whose slot is taken by another thread falls back to a ThreadLocal.
* workers' crowded thread-local maps. Frames therefore live in thread slots the engine owns, so a closed engine
* leaves nothing behind on its pooled workers.
*/
final class EngineThreadState {
private static final int SLOTS = 256;
private final AtomicReferenceArray<Frame> slots = new AtomicReferenceArray<>(SLOTS);
private final ThreadLocal<Frame> overflow = new ThreadLocal<>();
private final AtomicInteger overflowFrames = new AtomicInteger();
private final ThreadSlots<Frame> frames = ThreadSlots.bindings();
Frame current() {
Thread thread = Thread.currentThread();
Frame frame = slots.getPlain(slot(thread));
if (frame != null && frame.owner == thread) {
return frame;
}
return overflowFrames.get() == 0 ? null : overflow.get();
return frames.get();
}
GenerationRuntimeBinding binding() {
@@ -122,13 +110,8 @@ final class EngineThreadState {
if (frame != null) {
return frame;
}
Thread thread = Thread.currentThread();
frame = new Frame(thread);
if (!slots.compareAndSet(slot(thread), null, frame)) {
frame.overflow = true;
overflow.set(frame);
overflowFrames.incrementAndGet();
}
frame = new Frame();
frames.set(frame);
return frame;
}
@@ -136,27 +119,12 @@ final class EngineThreadState {
if (frame.assembly != null || frame.environment != null || frame.binding != null) {
return;
}
if (frame.overflow) {
overflow.remove();
overflowFrames.decrementAndGet();
return;
}
slots.compareAndSet(slot(frame.owner), frame, null);
}
private static int slot(Thread thread) {
return (int) thread.threadId() & (SLOTS - 1);
frames.remove();
}
static final class Frame {
private final Thread owner;
private boolean overflow;
RuntimeAssembly assembly;
BiomeEnvironmentBinding environment;
GenerationRuntimeBinding binding;
private Frame(Thread owner) {
this.owner = owner;
}
}
}
@@ -155,9 +155,9 @@ public class IrisComplex implements DataProvider {
InferredType.SHORE
};
@Getter(AccessLevel.NONE)
private final transient ThreadLocal<GridBoundsCache> gridBoundsCache = ThreadLocal.withInitial(GridBoundsCache::new);
private final transient ThreadSlots<GridBoundsCache> gridBoundsCache = new ThreadSlots<>(GridBoundsCache::new);
@Getter(AccessLevel.NONE)
private final transient ThreadLocal<EffectiveWater.Chunks> effectiveChunks = ThreadLocal.withInitial(EffectiveWater.Chunks::new);
private final transient ThreadSlots<EffectiveWater.Chunks> effectiveChunks = new ThreadSlots<>(EffectiveWater.Chunks::new);
@Getter(AccessLevel.NONE)
private final int biomeBoundsSamplingStep;
private transient volatile SharedCornerBounds sharedCornerBounds;
@@ -37,6 +37,7 @@ import art.arcane.iris.generation.noise.IrisGenerator;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.noise.IrisNoiseGenerator;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingEntry;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.structure.object.IrisObjectPlacement;
import art.arcane.iris.world.entity.IrisEffect;
@@ -75,6 +76,8 @@ public final class PackRuntime {
ore -> new SeedTable<>(ORE_CHANCE_SEED_CAPACITY, seed -> ore.createChance(seed, this)));
private final RuntimeTable<IrisObjectPlacement, SeedTable<CNG>> surfaceWarps = new RuntimeTable<>(
placement -> new SeedTable<>(SURFACE_WARP_SEED_CAPACITY, seed -> placement.createSurfaceWarp(seed, this)));
private final ThreadSlots<IrisDimensionCarvingResolver.State> carvingResolverStates =
new ThreadSlots<>(IrisDimensionCarvingResolver.State::new);
private final RuntimeTable<IrisEffect, ChronoLatch> effectLatches =
new RuntimeTable<>(effect -> new ChronoLatch(effect.getInterval()));
private final RuntimeTable<IrisDecorator, DecoratorRuntime> decorators =
@@ -187,6 +190,11 @@ public final class PackRuntime {
return surfaceWarps.get(placement).get(seed);
}
/** Carving lookups that are not handed a resolver state memoize their roots in the calling thread's state. */
public IrisDimensionCarvingResolver.State carvingResolverState() {
return carvingResolverStates.get();
}
/** Every player and entity of this owner shares one interval latch per effect. */
public ChronoLatch effectLatch(IrisEffect effect) {
return effectLatches.get(effect);
@@ -19,51 +19,113 @@
package art.arcane.iris.generation.runtime;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.function.Supplier;
/**
* Per-thread values owned by the object that holds this table, typically an engine-owned runtime. Unlike a
* ThreadLocal, the values live here and not in the worker threads, so they become unreachable with their owner even
* while the pooled workers that filled them stay alive. The table has a fixed size: a slot whose thread has died is
* reused, and when every probed slot belongs to a live thread the first one is taken over, which only costs that
* thread its memo.
* while the pooled workers that filled them stay alive. A live thread never loses its value: a thread whose probed
* slots all belong to other live threads keeps its value in an overflow map, which drops dead threads whenever it
* takes a new one. The size therefore follows the live threads and not the worker churn.
*/
public final class ThreadSlots<T> {
private static final int SLOT_COUNT = 256;
private static final int SLOT_MASK = SLOT_COUNT - 1;
private static final int PROBE_LIMIT = 8;
private static final int NOT_FOUND = -1;
private final AtomicReferenceArray<Slot<T>> slots = new AtomicReferenceArray<>(SLOT_COUNT);
private final ConcurrentHashMap<Thread, T> overflow = new ConcurrentHashMap<>();
private final Supplier<T> factory;
/** A table whose threads each get a value from the factory on first use. */
public ThreadSlots(Supplier<T> factory) {
this.factory = Objects.requireNonNull(factory, "thread value factory");
}
public T get() {
Thread thread = Thread.currentThread();
int home = (int) thread.threadId() & SLOT_MASK;
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
Slot<T> slot = slots.getPlain((home + probe) & SLOT_MASK);
if (slot != null && slot.owner == thread) {
return slot.value;
}
}
return claim(thread, home);
private ThreadSlots() {
this.factory = null;
}
private T claim(Thread thread, int home) {
Slot<T> created = new Slot<>(thread, factory.get());
/** A table of values each thread binds with {@link #set} and clears with {@link #remove}. */
public static <T> ThreadSlots<T> bindings() {
return new ThreadSlots<>();
}
/** This thread's value, created by the factory on first use; null for an unbound thread of a bindings table. */
public T get() {
Thread thread = Thread.currentThread();
int index = find(thread);
if (index != NOT_FOUND) {
return slots.getPlain(index).value();
}
T overflowed = overflow.isEmpty() ? null : overflow.get(thread);
if (overflowed != null || factory == null) {
return overflowed;
}
T created = factory.get();
store(thread, created);
return created;
}
public void set(T value) {
if (value == null) {
remove();
return;
}
Thread thread = Thread.currentThread();
int index = find(thread);
if (index != NOT_FOUND) {
slots.set(index, new Slot<>(thread, value));
return;
}
if (overflow.replace(thread, value) == null) {
store(thread, value);
}
}
public void remove() {
Thread thread = Thread.currentThread();
int index = find(thread);
if (index != NOT_FOUND) {
slots.set(index, null);
return;
}
if (!overflow.isEmpty()) {
overflow.remove(thread);
}
}
private int find(Thread thread) {
int home = home(thread);
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
int index = (home + probe) & SLOT_MASK;
Slot<T> slot = slots.getPlain(index);
if (slot != null && slot.owner() == thread) {
return index;
}
}
return NOT_FOUND;
}
private void store(Thread thread, T value) {
Slot<T> created = new Slot<>(thread, value);
int home = home(thread);
for (int probe = 0; probe < PROBE_LIMIT; probe++) {
int index = (home + probe) & SLOT_MASK;
Slot<T> current = slots.get(index);
if ((current == null || !current.owner.isAlive()) && slots.compareAndSet(index, current, created)) {
return created.value;
if ((current == null || !current.owner().isAlive()) && slots.compareAndSet(index, current, created)) {
return;
}
}
slots.set(home, created);
return created.value;
overflow.keySet().removeIf(owner -> !owner.isAlive());
overflow.put(thread, value);
}
private static int home(Thread thread) {
return (int) thread.threadId() & SLOT_MASK;
}
private record Slot<T>(Thread owner, T value) {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.subterrain;
import art.arcane.iris.generation.runtime.ThreadSlots;
import java.util.Objects;
public final class SubterrainPlan {
@@ -12,7 +13,7 @@ public final class SubterrainPlan {
private final SubterrainBounds bounds;
private final double shapePhase;
private final long shapeSeed;
private final ThreadLocal<ColumnCache> columnCache = ThreadLocal.withInitial(ColumnCache::new);
private final ThreadSlots<ColumnCache> columnCache = new ThreadSlots<>(ColumnCache::new);
SubterrainPlan(Options options) {
definition = Objects.requireNonNull(options.definition());
@@ -23,8 +23,6 @@ import java.util.Map;
public final class IrisDimensionCarvingResolver {
private static final int MAX_CHILD_DEPTH = 32;
private static final long CHILD_SEED_SALT = 0x9E3779B97F4A7C15L;
private static final ThreadLocal<WeakReference<State>> THREAD_STATE =
ThreadLocal.withInitial(() -> new WeakReference<>(null));
private IrisDimensionCarvingResolver() {
@@ -35,7 +33,7 @@ public final class IrisDimensionCarvingResolver {
}
public static IrisBiome resolveBiome(Engine engine, int worldX, int worldY, int worldZ, State state) {
State resolvedState = state == null ? threadState() : state;
State resolvedState = state == null ? threadState(engine) : state;
IrisData data = resolvedState.bind(engine);
IrisDimensionCarvingEntry root = resolveBoundRootEntry(engine, worldY, data, resolvedState);
if (root == null) {
@@ -46,21 +44,21 @@ public final class IrisDimensionCarvingResolver {
}
public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY) {
return resolveRootEntry(engine, worldY, threadState());
return resolveRootEntry(engine, worldY, threadState(engine));
}
public static IrisDimensionCarvingEntry resolveRootEntry(Engine engine, int worldY, State state) {
State resolvedState = state == null ? threadState() : state;
State resolvedState = state == null ? threadState(engine) : state;
IrisData data = resolvedState.bind(engine);
return resolveBoundRootEntry(engine, worldY, data, resolvedState);
}
public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldY, int worldZ) {
return resolveFromRoot(engine, rootEntry, worldX, worldY, worldZ, threadState());
return resolveFromRoot(engine, rootEntry, worldX, worldY, worldZ, threadState(engine));
}
public static IrisDimensionCarvingEntry resolveFromRoot(Engine engine, IrisDimensionCarvingEntry rootEntry, int worldX, int worldY, int worldZ, State state) {
State resolvedState = state == null ? threadState() : state;
State resolvedState = state == null ? threadState(engine) : state;
IrisData data = resolvedState.bind(engine);
return resolveBoundFromRoot(engine, rootEntry, worldX, worldY, worldZ, data, resolvedState);
}
@@ -314,15 +312,10 @@ public final class IrisDimensionCarvingResolver {
return state.childSeed;
}
private static State threadState() {
WeakReference<State> reference = THREAD_STATE.get();
State state = reference.get();
if (state != null) {
return state;
}
State replacement = new State();
THREAD_STATE.set(new WeakReference<>(replacement));
return replacement;
/** The calling thread's resolver state for this engine; engines without a pack runtime resolve unmemoized. */
private static State threadState(Engine engine) {
PackRuntime runtime = engine.getPackRuntime();
return runtime == null ? new State() : runtime.carvingResolverState();
}
public static final class Snapshot {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.terrain;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.cache.ConcurrentClockCache;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.biome.IrisBiome;
@@ -33,7 +34,7 @@ public final class Terrain3DRuntime {
private final Terrain3DFragmentFilter fragments;
private final Object profileLock = new Object();
private volatile Map<IrisTerrain3D, CompiledProfile> profiles = new IdentityHashMap<>();
private final ThreadLocal<ColumnMemo> localColumn = ThreadLocal.withInitial(ColumnMemo::new);
private final ThreadSlots<ColumnMemo> localColumn = new ThreadSlots<>(ColumnMemo::new);
private volatile Object cacheGeneration = new Object();
public Terrain3DRuntime(Sources sources, Options options) {
@@ -1,5 +1,6 @@
package art.arcane.iris.world.history;
import art.arcane.iris.generation.runtime.ThreadSlots;
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongArrays;
@@ -619,7 +620,7 @@ public final class GenerationBoundaryStore {
private final long[] regionKeys;
private final Long2ObjectOpenHashMap<String> shardHashes;
private final LinkedHashMap<Long, byte[]> masks;
private final ThreadLocal<RegionMask> lastRegion = new ThreadLocal<>();
private final ThreadSlots<RegionMask> lastRegion = ThreadSlots.bindings();
private MaskSource(
Path directory,
@@ -1,5 +1,6 @@
package art.arcane.iris.world.history;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.volmlib.nativelib.terrain.NativeGenerationRoute;
import art.arcane.volmlib.nativelib.terrain.NativeBlockPositionPredicate;
@@ -49,7 +50,7 @@ public final class GenerationHistoryRuntimeRouter implements AutoCloseable {
private final ReentrantLock stateLock;
private final Condition inactive;
private final ThreadLocal<Integer> operationDepth;
private final ThreadLocal<RuntimeRoute> scopedRoute;
private final ThreadSlots<RuntimeRoute> scopedRoute;
private int activeOperations;
private int activeLoads;
private boolean closed;
@@ -72,7 +73,7 @@ public final class GenerationHistoryRuntimeRouter implements AutoCloseable {
this.stateLock = new ReentrantLock();
this.inactive = stateLock.newCondition();
this.operationDepth = ThreadLocal.withInitial(() -> 0);
this.scopedRoute = new ThreadLocal<>();
this.scopedRoute = ThreadSlots.bindings();
this.biomes = new SavedBiomeRuntime(engine, history);
this.objectContinuations = new HistoricalObjectContinuations(history, this::readObjectContinuationRegion);
@@ -1,5 +1,6 @@
package art.arcane.iris.world.history;
import art.arcane.iris.generation.runtime.ThreadSlots;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.AtomicReferenceArray;
@@ -9,7 +10,7 @@ final class TransitionBandIndex {
private final GenerationBoundary boundary;
private final TransitionBoundarySampler sampler;
private final AtomicReferenceArray<Region> regions = new AtomicReferenceArray<>(MAXIMUM_CACHED_REGIONS);
private final ThreadLocal<Region> lastRegion = new ThreadLocal<>();
private final ThreadSlots<Region> lastRegion = ThreadSlots.bindings();
TransitionBandIndex(GenerationBoundary boundary, TransitionBoundarySampler sampler) {
this.boundary = boundary;
@@ -1,5 +1,6 @@
package art.arcane.iris.world.history;
import art.arcane.iris.generation.runtime.ThreadSlots;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
@@ -21,7 +22,7 @@ final class TransitionBoundarySampler {
private final TerrainBoundarySignatureStore.Snapshot signatures;
private final LinkedHashMap<Long, CandidateIndex> chunkCandidates;
private final Map<Long, CompletableFuture<CandidateIndex>> pendingCandidates = new HashMap<>();
private final ThreadLocal<ChunkCache> cache;
private final ThreadSlots<ChunkCache> cache;
private int cachedCandidates;
private long candidateBuildCount;
@@ -36,7 +37,7 @@ final class TransitionBoundarySampler {
this.searchWidth = terrainWidth;
this.signatures = Objects.requireNonNull(signatures, "Terrain boundary signatures");
this.chunkCandidates = new LinkedHashMap<>(MAXIMUM_CACHED_CHUNKS, 0.75F, true);
this.cache = ThreadLocal.withInitial(ChunkCache::new);
this.cache = new ThreadSlots<>(ChunkCache::new);
}
TransitionGenerationPlan.TerrainSample sample(int blockX, int blockZ) {
@@ -1,5 +1,6 @@
package art.arcane.iris.world.history;
import art.arcane.iris.generation.runtime.ThreadSlots;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
@@ -15,7 +16,7 @@ public final class TransitionDisplacementField {
private final Sources sources;
private final LinkedHashMap<Long, ChunkField> completed = new LinkedHashMap<>(64, 0.75F, true);
private final ConcurrentHashMap<Long, CompletableFuture<ChunkField>> pending = new ConcurrentHashMap<>();
private final ThreadLocal<ChunkField> local = new ThreadLocal<>();
private final ThreadSlots<ChunkField> local = ThreadSlots.bindings();
public TransitionDisplacementField(TransitionGenerationPlan plan, Sources sources) {
this.plan = Objects.requireNonNull(plan);
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.ThreadSlots;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.generation.runtime.Engine;
@@ -378,7 +379,7 @@ public class IrisCaveCarver3DNearParityTest {
}
Field scratchField = IrisCaveCarver3D.class.getDeclaredField("scratchCache");
scratchField.setAccessible(true);
ThreadLocal<?> scratchCache = (ThreadLocal<?>) scratchField.get(carver);
ThreadSlots<?> scratchCache = (ThreadSlots<?>) scratchField.get(carver);
CaveCarveScratch scratch = (CaveCarveScratch) scratchCache.get();
assertTrue(scratch.sectionMatter.length > 0);
for (Matter matter : scratch.sectionMatter) {
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.runtime.PackRuntime;
import art.arcane.iris.generation.terrain.transform.IrisTerrainTransform;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction;
@@ -366,6 +367,7 @@ public class MantleCarvedTerrainTest {
case "getWorld" -> world;
case "getPlatformHooks" -> hooks;
case "getData" -> null;
case "getPackRuntime" -> null;
default -> InvocationHandler.invokeDefault(proxy, method, arguments);
});
}
@@ -143,6 +143,7 @@ public class EngineBiomeColumnTest {
case "getData" -> data;
case "getDimension" -> dimension;
case "getWorld" -> world;
case "getPackRuntime" -> null;
default -> InvocationHandler.invokeDefault(proxy, method, arguments);
});
}
@@ -171,7 +171,7 @@ public class IrisComplexChunkCornersTest {
Class<?> cacheClass = Class.forName("art.arcane.iris.generation.runtime.IrisComplex$GridBoundsCache");
Constructor<?> cacheConstructor = cacheClass.getDeclaredConstructor();
cacheConstructor.setAccessible(true);
setField(complex, "gridBoundsCache", ThreadLocal.withInitial(() -> newCache(cacheConstructor)));
setField(complex, "gridBoundsCache", new ThreadSlots<>(() -> newCache(cacheConstructor)));
return complex;
}
@@ -247,7 +247,7 @@ public class IrisComplexGridBoundsCacheTest {
Class<?> cacheClass = Class.forName("art.arcane.iris.generation.runtime.IrisComplex$GridBoundsCache");
Constructor<?> cacheConstructor = cacheClass.getDeclaredConstructor();
cacheConstructor.setAccessible(true);
ThreadLocal<Object> cache = ThreadLocal.withInitial(() -> newCache(cacheConstructor));
ThreadSlots<Object> cache = new ThreadSlots<>(() -> newCache(cacheConstructor));
Field gridBoundsCache = IrisComplex.class.getDeclaredField("gridBoundsCache");
gridBoundsCache.setAccessible(true);
gridBoundsCache.set(complex, cache);
@@ -295,7 +295,7 @@ public class IrisComplexGridBoundsCacheTest {
private static long invokeCornerBounds(IrisComplex complex, Method method, IrisInterpolator interpolator, int x, int z) throws Exception {
Field gridBoundsCache = IrisComplex.class.getDeclaredField("gridBoundsCache");
gridBoundsCache.setAccessible(true);
ThreadLocal<?> cache = (ThreadLocal<?>) gridBoundsCache.get(complex);
ThreadSlots<?> cache = (ThreadSlots<?>) gridBoundsCache.get(complex);
return (long) method.invoke(complex, cache.get(), null, interpolator, 0, new IrisGenerator[0], x, z);
}
@@ -18,6 +18,10 @@
package art.arcane.iris.generation.runtime;
import static org.junit.Assert.assertNull;
import java.util.concurrent.CountDownLatch;
import java.util.List;
import java.util.ArrayList;
import org.junit.Test;
import java.lang.reflect.Field;
@@ -71,6 +75,51 @@ public class ThreadSlotsTest {
assertEquals("The table must stay at its fixed size", 256, slotCount(slots));
}
@Test
public void bindingsStayUnsetUntilBoundAndClearOnRemove() {
ThreadSlots<Object> bindings = ThreadSlots.bindings();
Object value = new Object();
assertNull(bindings.get());
bindings.set(value);
assertSame(value, bindings.get());
bindings.remove();
assertNull(bindings.get());
}
@Test
public void liveThreadsBeyondTheProbedSlotsKeepTheirValues() throws Exception {
ThreadSlots<Object> slots = new ThreadSlots<>(Object::new);
int threads = 300;
CountDownLatch filled = new CountDownLatch(threads);
CountDownLatch release = new CountDownLatch(1);
AtomicInteger lost = new AtomicInteger();
List<Thread> workers = new ArrayList<>();
for (int index = 0; index < threads; index++) {
Thread worker = new Thread(() -> {
Object first = slots.get();
filled.countDown();
try {
release.await();
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
}
if (slots.get() != first) {
lost.incrementAndGet();
}
});
workers.add(worker);
worker.start();
}
filled.await();
release.countDown();
for (Thread worker : workers) {
worker.join();
}
assertEquals(0, lost.get());
}
private static int slotCount(ThreadSlots<?> slots) throws ReflectiveOperationException {
Field field = ThreadSlots.class.getDeclaredField("slots");
field.setAccessible(true);
@@ -472,12 +472,12 @@ public class IrisDimensionCarvingResolverParityTest {
}
@Test(timeout = 20_000L)
public void longLivedWorkerDoesNotRetainPopulatedThreadLocalStateOrEngine() throws Exception {
public void longLivedWorkerDoesNotRetainPopulatedResolverStateOrEngine() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
CountDownLatch blockerStarted = new CountDownLatch(1);
CountDownLatch releaseBlocker = new CountDownLatch(1);
try {
LifetimeReferences references = executor.submit(this::populateThreadLocalLifetimeReferences).get();
LifetimeReferences references = executor.submit(this::populateResolverStateLifetimeReferences).get();
Future<?> blocker = executor.submit(() -> {
blockerStarted.countDown();
releaseBlocker.await();
@@ -496,31 +496,22 @@ public class IrisDimensionCarvingResolverParityTest {
}
}
private LifetimeReferences populateThreadLocalLifetimeReferences() throws Exception {
private LifetimeReferences populateResolverStateLifetimeReferences() throws Exception {
RetainedFixture fixture = createRetainedFixture();
assertNotNull(IrisDimensionCarvingResolver.resolveRootEntry(fixture.engine(), 80));
Field threadStateField = IrisDimensionCarvingResolver.class.getDeclaredField("THREAD_STATE");
threadStateField.setAccessible(true);
ThreadLocal<?> threadState = (ThreadLocal<?>) threadStateField.get(null);
Object value = threadState.get();
assertTrue(value instanceof WeakReference<?>);
@SuppressWarnings("unchecked")
WeakReference<IrisDimensionCarvingResolver.State> state =
(WeakReference<IrisDimensionCarvingResolver.State>) value;
IrisDimensionCarvingResolver.State populatedState = state.get();
assertNotNull(populatedState);
IrisDimensionCarvingResolver.State populatedState = fixture.engine().getPackRuntime().carvingResolverState();
Field biomeCacheField = IrisDimensionCarvingResolver.State.class.getDeclaredField("biomeCache");
biomeCacheField.setAccessible(true);
assertFalse(((Map<?, ?>) biomeCacheField.get(populatedState)).isEmpty());
return new LifetimeReferences(
state,
new WeakReference<>(populatedState),
new WeakReference<>(fixture.engine()));
}
private static void awaitCollection(LifetimeReferences references) {
AtomicInteger attempt = new AtomicInteger();
Await.reached("the thread-local State and Engine to be collected", Duration.ofSeconds(5L), () -> {
Await.reached("the resolver State and Engine to be collected", Duration.ofSeconds(5L), () -> {
System.gc();
if (references.state().get() == null
&& references.engine().get() == null) {
@@ -530,7 +521,7 @@ public class IrisDimensionCarvingResolverParityTest {
pressure[0] = (byte) attempt.incrementAndGet();
return false;
});
assertTrue("Thread-local State was retained", references.state().get() == null);
assertTrue("Resolver State was retained", references.state().get() == null);
assertTrue("Engine was retained", references.engine().get() == null);
}
@@ -566,17 +557,20 @@ public class IrisDimensionCarvingResolverParityTest {
IrisDimension dimension = new IrisDimension();
dimension.setCarving(carvingEntries);
AtomicReference<PackRuntime> runtime = new AtomicReference<>();
Engine engine = (Engine) Proxy.newProxyInstance(
Engine.class.getClassLoader(),
new Class<?>[]{Engine.class},
(proxy, method, arguments) -> switch (method.getName()) {
case "getDimension" -> dimension;
case "getData" -> data;
case "getPackRuntime" -> runtime.get();
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == arguments[0];
case "toString" -> "carving-retention-test-engine";
default -> throw new UnsupportedOperationException(method.toString());
});
runtime.set(PackRuntime.forEngine(engine, data));
return new RetainedFixture(engine, entry);
}
@@ -196,17 +196,6 @@ public class PackRuntimeStateGateTest {
);
private static final List<Entry> PENDING_MIGRATION = List.of(
pending("art.arcane.iris.generation.bake.ChunkBakeCache", "recent", Kind.THREAD),
pending("art.arcane.iris.generation.hydrology.engine.HydrologyRuntime", "last", Kind.THREAD),
pending("art.arcane.iris.generation.mantle.IrisCaveCarver3D", "scratchCache", Kind.THREAD),
pending("art.arcane.iris.generation.mantle.MantleWriter", "objectPlacementCapture", Kind.THREAD),
pending("art.arcane.iris.generation.mantle.MantleWriter", "objectWater", Kind.THREAD),
pending("art.arcane.iris.generation.runtime.EngineThreadState", "overflow", Kind.THREAD),
pending("art.arcane.iris.generation.runtime.IrisComplex", "effectiveChunks", Kind.THREAD),
pending("art.arcane.iris.generation.runtime.IrisComplex", "gridBoundsCache", Kind.THREAD),
pending("art.arcane.iris.generation.subterrain.SubterrainPlan", "columnCache", Kind.THREAD),
pending("art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver", "THREAD_STATE", Kind.THREAD),
pending("art.arcane.iris.generation.terrain.Terrain3DRuntime", "localColumn", Kind.THREAD),
pending("art.arcane.iris.structure.graph.StructureGraphCatalog", "CACHE", Kind.STATIC),
pending("art.arcane.iris.structure.graph.StructureGraphCatalog", "RUNTIME_OUTPUT", Kind.STATIC),
pending("art.arcane.iris.structure.nativegen.NativeStructureOwnershipStore", "STATES", Kind.STATIC),
@@ -215,11 +204,6 @@ public class PackRuntimeStateGateTest {
pending("art.arcane.iris.structure.placement.IrisStructureLocator", "LOCATABLE_INDEX_CACHE", Kind.STATIC),
pending("art.arcane.iris.structure.placement.StructureReachability", "REACHABLE_CACHE", Kind.STATIC),
pending("art.arcane.iris.studio.object.ObjectStudioActivation", "SOURCES", Kind.STATIC),
pending("art.arcane.iris.world.history.GenerationBoundaryStore$MaskSource", "lastRegion", Kind.THREAD),
pending("art.arcane.iris.world.history.GenerationHistoryRuntimeRouter", "scopedRoute", Kind.THREAD),
pending("art.arcane.iris.world.history.TransitionBandIndex", "lastRegion", Kind.THREAD),
pending("art.arcane.iris.world.history.TransitionBoundarySampler", "cache", Kind.THREAD),
pending("art.arcane.iris.world.history.TransitionDisplacementField", "local", Kind.THREAD),
pending("art.arcane.iris.generation.bake.ChunkBakeCache", "SPARSE", Kind.SCRATCH),
pending("art.arcane.iris.generation.context.IrisContext", "OVERFLOW", Kind.SCRATCH),
pending("art.arcane.iris.generation.decoration.DecoratorCore", "SCRATCH_OPTS", Kind.SCRATCH),