From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: wangxyper Date: Sun, 15 Jan 2023 09:52:27 +0800 Subject: [PATCH] Hearse: Paper chunk system changes Original license: MIT Original project: https://github.com/NaturalCodeClub/Hearse diff --git a/src/main/java/io/papermc/paper/chunk/PlayerChunkLoader.java b/src/main/java/io/papermc/paper/chunk/PlayerChunkLoader.java index 0b060183429f4c72ec767075538477b4302bbf0d..028b23f5c23bbfd83498c3e06a56079ceb0798ad 100644 --- a/src/main/java/io/papermc/paper/chunk/PlayerChunkLoader.java +++ b/src/main/java/io/papermc/paper/chunk/PlayerChunkLoader.java @@ -7,9 +7,9 @@ import io.papermc.paper.util.CoordinateUtils; import io.papermc.paper.util.IntervalledCounter; import io.papermc.paper.util.TickThread; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; -import it.unimi.dsi.fastutil.objects.Reference2IntOpenHashMap; -import it.unimi.dsi.fastutil.objects.Reference2ObjectLinkedOpenHashMap; -import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet; +import it.unimi.dsi.fastutil.longs.LongSet; +import it.unimi.dsi.fastutil.longs.LongSets; +import it.unimi.dsi.fastutil.objects.*; import net.minecraft.network.protocol.game.ClientboundSetChunkCacheCenterPacket; import net.minecraft.network.protocol.game.ClientboundSetChunkCacheRadiusPacket; import net.minecraft.network.protocol.game.ClientboundSetSimulationDistancePacket; @@ -22,10 +22,10 @@ import net.minecraft.world.level.chunk.LevelChunk; import org.apache.commons.lang3.mutable.MutableObject; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.entity.Player; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.List; -import java.util.TreeSet; + +import java.util.*; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.atomic.AtomicInteger; public final class PlayerChunkLoader { @@ -76,10 +76,10 @@ public final class PlayerChunkLoader { } protected final ChunkMap chunkMap; - protected final Reference2ObjectLinkedOpenHashMap playerMap = new Reference2ObjectLinkedOpenHashMap<>(512, 0.7f); - protected final ReferenceLinkedOpenHashSet chunkSendQueue = new ReferenceLinkedOpenHashSet<>(512, 0.7f); + protected final Reference2ObjectMap playerMap = Reference2ObjectMaps.synchronize(new Reference2ObjectLinkedOpenHashMap<>(512, 0.7f)); + protected final Deque chunkSendQueue = new ConcurrentLinkedDeque<>(); - protected final TreeSet chunkLoadQueue = new TreeSet<>((final PlayerLoaderData p1, final PlayerLoaderData p2) -> { + protected final NavigableSet chunkLoadQueue = new ConcurrentSkipListSet<>((final PlayerLoaderData p1, final PlayerLoaderData p2) -> { if (p1 == p2) { return 0; } @@ -109,7 +109,7 @@ public final class PlayerChunkLoader { return Integer.compare(System.identityHashCode(p1), System.identityHashCode(p2)); }); - protected final TreeSet chunkSendWaitQueue = new TreeSet<>((final PlayerLoaderData p1, final PlayerLoaderData p2) -> { + protected final NavigableSet chunkSendWaitQueue = new ConcurrentSkipListSet<>((final PlayerLoaderData p1, final PlayerLoaderData p2) -> { if (p1 == p2) { return 0; } @@ -308,8 +308,8 @@ public final class PlayerChunkLoader { }); } - protected final LongOpenHashSet isTargetedForPlayerLoad = new LongOpenHashSet(); - protected final LongOpenHashSet chunkTicketTracker = new LongOpenHashSet(); + protected final LongSet isTargetedForPlayerLoad = LongSets.synchronize(new LongOpenHashSet()); + protected final LongSet chunkTicketTracker = LongSets.synchronize(new LongOpenHashSet()); public boolean isChunkNearPlayers(final int chunkX, final int chunkZ) { final PooledLinkedHashSets.PooledObjectLinkedOpenHashSet playersInSendRange = this.broadcastMap.getObjectsInRange(chunkX, chunkZ); @@ -373,7 +373,7 @@ public final class PlayerChunkLoader { } return !(data.hasSentChunk(chunkX - 1, chunkZ) && data.hasSentChunk(chunkX + 1, chunkZ) && - data.hasSentChunk(chunkX, chunkZ - 1) && data.hasSentChunk(chunkX, chunkZ + 1)); + data.hasSentChunk(chunkX, chunkZ - 1) && data.hasSentChunk(chunkX, chunkZ + 1)); } protected int getMaxConcurrentChunkSends() { @@ -523,17 +523,16 @@ public final class PlayerChunkLoader { if (time < nextChunkSend) { return; } + PlayerLoaderData data1; // drain entries from wait queue - while (!this.chunkSendWaitQueue.isEmpty()) { - final PlayerLoaderData data = this.chunkSendWaitQueue.first(); - - if (data.nextChunkSendTarget > time) { + while ((data1 = this.chunkSendWaitQueue.pollFirst())!=null) { + if (data1.nextChunkSendTarget > time) { break; } this.chunkSendWaitQueue.pollFirst(); - this.chunkSendQueue.add(data); + this.chunkSendQueue.add(data1); } if (this.chunkSendQueue.isEmpty()) { @@ -542,10 +541,9 @@ public final class PlayerChunkLoader { final int maxSends = this.getMaxConcurrentChunkSends(); final long nextPlayerDeadline = this.getTargetSendPerPlayerAddend() + time; - for (;;) { - if (this.chunkSendQueue.isEmpty()) { - break; - } + final Deque tempCopy = new ArrayDeque<>(this.chunkSendQueue); + PlayerLoaderData data; + while ((data = tempCopy.pollFirst())!=null) { final int currSends = concurrentChunkSends.get(); if (currSends >= maxSends) { break; @@ -554,19 +552,12 @@ public final class PlayerChunkLoader { if (!concurrentChunkSends.compareAndSet(currSends, currSends + 1)) { continue; } - // send chunk - - final PlayerLoaderData data = this.chunkSendQueue.removeFirst(); - + this.chunkSendQueue.remove(data); final ChunkPriorityHolder queuedSend = data.sendQueue.pollFirst(); if (queuedSend == null) { concurrentChunkSends.getAndDecrement(); // we never sent, so decrease // stop iterating over players who have nothing to send - if (this.chunkSendQueue.isEmpty()) { - // nothing left - break; - } continue; } @@ -581,17 +572,18 @@ public final class PlayerChunkLoader { this.sendingChunkCounts.addTo(data, 1); } + final PlayerLoaderData finalData = data; data.sendChunk(queuedSend.chunkX, queuedSend.chunkZ, () -> { synchronized (this.sendingChunkCounts) { - final int count = this.sendingChunkCounts.getInt(data); + final int count = this.sendingChunkCounts.getInt(finalData); if (count == 0) { // disconnected, so we don't need to decrement: it will be decremented for us return; } if (count == 1) { - this.sendingChunkCounts.removeInt(data); + this.sendingChunkCounts.removeInt(finalData); } else { - this.sendingChunkCounts.put(data, count - 1); + this.sendingChunkCounts.put(finalData, count - 1); } } @@ -618,16 +610,12 @@ public final class PlayerChunkLoader { final int maxLoads = this.getMaxChunkLoads(); final long time = System.nanoTime(); boolean updatedCounters = false; - for (;;) { - final PlayerLoaderData data = this.chunkLoadQueue.pollFirst(); - + PlayerLoaderData data; + while ((data = this.chunkLoadQueue.pollFirst())!=null) { data.lastChunkLoad = time; final ChunkPriorityHolder queuedLoad = data.loadQueue.peekFirst(); if (queuedLoad == null) { - if (this.chunkLoadQueue.isEmpty()) { - break; - } continue; } @@ -673,7 +661,7 @@ public final class PlayerChunkLoader { final int currentChunkLoads = this.concurrentChunkLoads; if (currentChunkLoads >= maxLoads || (GlobalConfiguration.get().chunkLoading.globalMaxChunkLoadRate > 0 && (TICKET_ADDITION_COUNTER_SHORT.getRate() >= GlobalConfiguration.get().chunkLoading.globalMaxChunkLoadRate || TICKET_ADDITION_COUNTER_LONG.getRate() >= GlobalConfiguration.get().chunkLoading.globalMaxChunkLoadRate)) - || (GlobalConfiguration.get().chunkLoading.playerMaxChunkLoadRate > 0.0 && (data.ticketAdditionCounterShort.getRate() >= GlobalConfiguration.get().chunkLoading.playerMaxChunkLoadRate || data.ticketAdditionCounterLong.getRate() >= GlobalConfiguration.get().chunkLoading.playerMaxChunkLoadRate))) { + || (GlobalConfiguration.get().chunkLoading.playerMaxChunkLoadRate > 0.0 && (data.ticketAdditionCounterShort.getRate() >= GlobalConfiguration.get().chunkLoading.playerMaxChunkLoadRate || data.ticketAdditionCounterLong.getRate() >= GlobalConfiguration.get().chunkLoading.playerMaxChunkLoadRate))) { // don't poll, we didn't load it this.chunkLoadQueue.add(data); break; @@ -786,11 +774,11 @@ public final class PlayerChunkLoader { // warning: modifications of this field must be aware that the loadQueue inside PlayerChunkLoader uses this field // in a comparator! - protected final ArrayDeque loadQueue = new ArrayDeque<>(); - protected final LongOpenHashSet sentChunks = new LongOpenHashSet(); - protected final LongOpenHashSet chunksToBeSent = new LongOpenHashSet(); + protected final Deque loadQueue = new ConcurrentLinkedDeque<>(); + protected final LongSet sentChunks = LongSets.synchronize(new LongOpenHashSet()); + protected final LongSet chunksToBeSent = LongSets.synchronize(new LongOpenHashSet()); - protected final TreeSet sendQueue = new TreeSet<>((final ChunkPriorityHolder p1, final ChunkPriorityHolder p2) -> { + protected final NavigableSet sendQueue = new ConcurrentSkipListSet<>((final ChunkPriorityHolder p1, final ChunkPriorityHolder p2) -> { final int distanceCompare = Integer.compare(p1.manhattanDistanceToPlayer, p2.manhattanDistanceToPlayer); if (distanceCompare != 0) { return distanceCompare; @@ -964,14 +952,14 @@ public final class PlayerChunkLoader { && tickViewDistance == this.lastTickDistance && (this.usingLookingPriority ? ( - // has our block stayed the same (this also accounts for chunk change)? - Mth.floor(this.lastLocX) == Mth.floor(posX) + // has our block stayed the same (this also accounts for chunk change)? + Mth.floor(this.lastLocX) == Mth.floor(posX) && Mth.floor(this.lastLocZ) == Mth.floor(posZ) - ) : ( - // has our chunk stayed the same - (Mth.floor(this.lastLocX) >> 4) == (Mth.floor(posX) >> 4) + ) : ( + // has our chunk stayed the same + (Mth.floor(this.lastLocX) >> 4) == (Mth.floor(posX) >> 4) && (Mth.floor(this.lastLocZ) >> 4) == (Mth.floor(posZ) >> 4) - )) + )) // has our decision about look priority changed? && this.usingLookingPriority == useLookPriority diff --git a/src/main/java/io/papermc/paper/chunk/system/entity/EntityLookup.java b/src/main/java/io/papermc/paper/chunk/system/entity/EntityLookup.java index 61c170555c8854b102c640b0b6a615f9f732edbf..ec8982b89cde24eefd3d392eed3e6cc926053dff 100644 --- a/src/main/java/io/papermc/paper/chunk/system/entity/EntityLookup.java +++ b/src/main/java/io/papermc/paper/chunk/system/entity/EntityLookup.java @@ -6,8 +6,14 @@ import io.papermc.paper.util.CoordinateUtils; import io.papermc.paper.util.TickThread; import io.papermc.paper.util.WorldUtil; import io.papermc.paper.world.ChunkEntitySlices; +import it.unimi.dsi.fastutil.ints.Int2ReferenceMap; +import it.unimi.dsi.fastutil.ints.Int2ReferenceMaps; import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectMap; +import it.unimi.dsi.fastutil.longs.Long2ObjectMaps; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.objects.Object2ReferenceMap; +import it.unimi.dsi.fastutil.objects.Object2ReferenceMaps; import it.unimi.dsi.fastutil.objects.Object2ReferenceOpenHashMap; import net.minecraft.core.BlockPos; import io.papermc.paper.chunk.system.ChunkSystem; @@ -45,16 +51,16 @@ public final class EntityLookup implements LevelEntityGetter { public final ServerLevel world; - private final StampedLock stateLock = new StampedLock(); - protected final Long2ObjectOpenHashMap regions = new Long2ObjectOpenHashMap<>(128, 0.5f); + private final StampedLock entityByLock = new StampedLock(); + private final Object chunkEntitySlicesLock = new Object(); + + protected final Long2ObjectMap regions = Long2ObjectMaps.synchronize(new Long2ObjectOpenHashMap<>(128, 0.5f)); private final int minSection; // inclusive private final int maxSection; // inclusive private final LevelCallback worldCallback; - - private final StampedLock entityByLock = new StampedLock(); - private final Int2ReferenceOpenHashMap entityById = new Int2ReferenceOpenHashMap<>(); - private final Object2ReferenceOpenHashMap entityByUUID = new Object2ReferenceOpenHashMap<>(); + private final Int2ReferenceMap entityById = new Int2ReferenceOpenHashMap<>(); + private final Object2ReferenceMap entityByUUID = new Object2ReferenceOpenHashMap<>(); private final EntityList accessibleEntities = new EntityList(); public EntityLookup(final ServerLevel world, final LevelCallback worldCallback) { @@ -105,7 +111,6 @@ public final class EntityLookup implements LevelEntityGetter { if (attempt != 0L) { try { final Entity ret = this.entityByUUID.get(id); - if (this.entityByLock.validate(attempt)) { return maskNonAccessible(ret); } @@ -166,12 +171,12 @@ public final class EntityLookup implements LevelEntityGetter { } @Override - public boolean hasNext() { + public synchronized boolean hasNext() { return this.off < this.length; } @Override - public T next() { + public synchronized T next() { if (this.off >= this.length) { throw new NoSuchElementException(); } @@ -179,7 +184,7 @@ public final class EntityLookup implements LevelEntityGetter { } @Override - public void remove() { + public synchronized void remove() { throw new UnsupportedOperationException(); } } @@ -208,8 +213,8 @@ public final class EntityLookup implements LevelEntityGetter { public void get(final AABB box, final Consumer action) { List entities = new ArrayList<>(); this.getEntitiesWithoutDragonParts(null, box, entities, null); - for (int i = 0, len = entities.size(); i < len; ++i) { - action.accept(entities.get(i)); + for (Entity entity : entities) { + action.accept(entity); } } @@ -217,8 +222,8 @@ public final class EntityLookup implements LevelEntityGetter { public void get(final EntityTypeTest filter, final AABB box, final AbortableIterationConsumer action) { List entities = new ArrayList<>(); this.getEntitiesWithoutDragonParts(null, box, entities, null); - for (int i = 0, len = entities.size(); i < len; ++i) { - final U casted = filter.tryCast(entities.get(i)); + for (Entity entity : entities) { + final U casted = filter.tryCast(entity); if (casted != null && action.accept(casted).shouldAbort()) { break; } @@ -228,75 +233,50 @@ public final class EntityLookup implements LevelEntityGetter { public void entityStatusChange(final Entity entity, final ChunkEntitySlices slices, final Visibility oldVisibility, final Visibility newVisibility, final boolean moved, final boolean created, final boolean destroyed) { TickThread.ensureTickThread(entity, "Entity status change must only happen on the main thread"); - - if (entity.updatingSectionStatus) { - // recursive status update - LOGGER.error("Cannot recursively update entity chunk status for entity " + entity, new Throwable()); - return; - } - - final boolean entityStatusUpdateBefore = slices == null ? false : slices.startPreventingStatusUpdates(); - - if (entityStatusUpdateBefore) { - LOGGER.error("Cannot update chunk status for entity " + entity + " since entity chunk (" + slices.chunkX + "," + slices.chunkZ + ") is receiving update", new Throwable()); - return; - } - + final Boolean ticketBlockBefore = this.world.chunkTaskScheduler.chunkHolderManager.blockTicketUpdates(); try { - final Boolean ticketBlockBefore = this.world.chunkTaskScheduler.chunkHolderManager.blockTicketUpdates(); - try { - entity.updatingSectionStatus = true; - try { - if (created) { - EntityLookup.this.worldCallback.onCreated(entity); - } + if (created) { + EntityLookup.this.worldCallback.onCreated(entity); + } - if (oldVisibility == newVisibility) { - if (moved && newVisibility.isAccessible()) { - EntityLookup.this.worldCallback.onSectionChange(entity); - } - return; - } + if (oldVisibility == newVisibility) { + if (moved && newVisibility.isAccessible()) { + EntityLookup.this.worldCallback.onSectionChange(entity); + } + return; + } - if (newVisibility.ordinal() > oldVisibility.ordinal()) { - // status upgrade - if (!oldVisibility.isAccessible() && newVisibility.isAccessible()) { - this.accessibleEntities.add(entity); - EntityLookup.this.worldCallback.onTrackingStart(entity); - } + if (newVisibility.ordinal() > oldVisibility.ordinal()) { + // status upgrade + if (!oldVisibility.isAccessible() && newVisibility.isAccessible()) { + this.accessibleEntities.add(entity); + EntityLookup.this.worldCallback.onTrackingStart(entity); + } - if (!oldVisibility.isTicking() && newVisibility.isTicking()) { - EntityLookup.this.worldCallback.onTickingStart(entity); - } - } else { - // status downgrade - if (oldVisibility.isTicking() && !newVisibility.isTicking()) { - EntityLookup.this.worldCallback.onTickingEnd(entity); - } + if (!oldVisibility.isTicking() && newVisibility.isTicking()) { + EntityLookup.this.worldCallback.onTickingStart(entity); + } + } else { + // status downgrade + if (oldVisibility.isTicking() && !newVisibility.isTicking()) { + EntityLookup.this.worldCallback.onTickingEnd(entity); + } - if (oldVisibility.isAccessible() && !newVisibility.isAccessible()) { - this.accessibleEntities.remove(entity); - EntityLookup.this.worldCallback.onTrackingEnd(entity); - } - } + if (oldVisibility.isAccessible() && !newVisibility.isAccessible()) { + this.accessibleEntities.remove(entity); + EntityLookup.this.worldCallback.onTrackingEnd(entity); + } + } - if (moved && newVisibility.isAccessible()) { - EntityLookup.this.worldCallback.onSectionChange(entity); - } + if (moved && newVisibility.isAccessible()) { + EntityLookup.this.worldCallback.onSectionChange(entity); + } - if (destroyed) { - EntityLookup.this.worldCallback.onDestroyed(entity); - } - } finally { - entity.updatingSectionStatus = false; - } - } finally { - this.world.chunkTaskScheduler.chunkHolderManager.unblockTicketUpdates(ticketBlockBefore); + if (destroyed) { + EntityLookup.this.worldCallback.onDestroyed(entity); } } finally { - if (slices != null) { - slices.stopPreventingStatusUpdates(false); - } + this.world.chunkTaskScheduler.chunkHolderManager.unblockTicketUpdates(ticketBlockBefore); } } @@ -346,11 +326,6 @@ public final class EntityLookup implements LevelEntityGetter { return false; } - if (entity.updatingSectionStatus) { - LOGGER.warn("Entity " + entity + " is currently prevented from being added/removed to world since it is processing section status updates", new Throwable()); - return false; - } - if (fromDisk) { ChunkSystem.onEntityPreAdd(this.world, entity); if (entity.isRemoved()) { @@ -398,7 +373,10 @@ public final class EntityLookup implements LevelEntityGetter { if (!entity.isRemoved()) { throw new IllegalStateException("Only call Entity#setRemoved to remove an entity"); } - final ChunkEntitySlices slices = this.getChunk(sectionX, sectionZ); + ChunkEntitySlices slices; + synchronized (this.chunkEntitySlicesLock){ + slices = this.getChunk(sectionX, sectionZ); + } // all entities should be in a chunk if (slices == null) { LOGGER.warn("Cannot remove entity " + entity + " from null entity slices (" + sectionX + "," + sectionZ + ")"); @@ -441,7 +419,10 @@ public final class EntityLookup implements LevelEntityGetter { // ensure the old section is owned by this tick thread TickThread.ensureTickThread(this.world, entity.sectionX, entity.sectionZ, "Cannot move entity off-main"); - final ChunkEntitySlices old = this.getChunk(entity.sectionX, entity.sectionZ); + ChunkEntitySlices old; + synchronized (this.chunkEntitySlicesLock){ + old = this.getChunk(entity.sectionX, entity.sectionZ); + } final ChunkEntitySlices slices = this.getOrCreateChunk(newSectionX, newSectionZ); if (!old.removeEntity(entity, entity.sectionY)) { @@ -609,7 +590,7 @@ public final class EntityLookup implements LevelEntityGetter { continue; } - chunk.getEntities(type, box, (List)into, (Predicate)predicate); + chunk.getEntities(type, box, (List) into, (Predicate) predicate); } } } @@ -660,21 +641,24 @@ public final class EntityLookup implements LevelEntityGetter { TickThread.ensureTickThread(this.world, chunkX, chunkZ, "Cannot load in entity section off-main"); synchronized (this) { final ChunkEntitySlices curr = this.getChunk(chunkX, chunkZ); - if (curr != null) { - this.removeChunk(chunkX, chunkZ); - - curr.mergeInto(slices); - - this.addChunk(chunkX, chunkZ, slices); - } else { - this.addChunk(chunkX, chunkZ, slices); + synchronized (this.chunkEntitySlicesLock){ + if (curr != null) { + this.removeChunk(chunkX, chunkZ); + curr.mergeInto(slices); + this.addChunk(chunkX, chunkZ, slices); + } else { + this.addChunk(chunkX, chunkZ, slices); + } } } } + public void entitySectionUnload(final int chunkX, final int chunkZ) { TickThread.ensureTickThread(this.world, chunkX, chunkZ, "Cannot unload entity section off-main"); - this.removeChunk(chunkX, chunkZ); + synchronized (this.chunkEntitySlicesLock){ + this.removeChunk(chunkX, chunkZ); + } } public ChunkEntitySlices getChunk(final int chunkX, final int chunkZ) { @@ -699,27 +683,7 @@ public final class EntityLookup implements LevelEntityGetter { public ChunkSlicesRegion getRegion(final int regionX, final int regionZ) { final long key = CoordinateUtils.getChunkKey(regionX, regionZ); - final long attempt = this.stateLock.tryOptimisticRead(); - if (attempt != 0L) { - try { - final ChunkSlicesRegion ret = this.regions.get(key); - - if (this.stateLock.validate(attempt)) { - return ret; - } - } catch (final Error error) { - throw error; - } catch (final Throwable thr) { - // ignore - } - } - - this.stateLock.readLock(); - try { - return this.regions.get(key); - } finally { - this.stateLock.tryUnlockRead(); - } + return this.regions.get(key); } private synchronized void removeChunk(final int chunkX, final int chunkZ) { @@ -730,12 +694,7 @@ public final class EntityLookup implements LevelEntityGetter { final int remaining = region.remove(relIndex); if (remaining == 0) { - this.stateLock.writeLock(); - try { - this.regions.remove(key); - } finally { - this.stateLock.tryUnlockWrite(); - } + this.regions.remove(key); } } @@ -749,12 +708,7 @@ public final class EntityLookup implements LevelEntityGetter { } else { region = new ChunkSlicesRegion(); region.add(relIndex, slices); - this.stateLock.writeLock(); - try { - this.regions.put(key, region); - } finally { - this.stateLock.tryUnlockWrite(); - } + this.regions.put(key, region); } } @@ -831,9 +785,11 @@ public final class EntityLookup implements LevelEntityGetter { public static final NoOpCallback INSTANCE = new NoOpCallback(); @Override - public void onMove() {} + public void onMove() { + } @Override - public void onRemove(final Entity.RemovalReason reason) {} + public void onRemove(final Entity.RemovalReason reason) { + } } } diff --git a/src/main/java/io/papermc/paper/chunk/system/scheduling/ChunkHolderManager.java b/src/main/java/io/papermc/paper/chunk/system/scheduling/ChunkHolderManager.java index 830d863cd9665d58875bfa5ca2bcd22f89ab2d49..15eeea40bb7a44470f6f3f0e2473cb451812eec1 100644 --- a/src/main/java/io/papermc/paper/chunk/system/scheduling/ChunkHolderManager.java +++ b/src/main/java/io/papermc/paper/chunk/system/scheduling/ChunkHolderManager.java @@ -13,14 +13,10 @@ import io.papermc.paper.util.CoordinateUtils; import io.papermc.paper.util.TickThread; import io.papermc.paper.util.misc.Delayed8WayDistancePropagator2D; import io.papermc.paper.world.ChunkEntitySlices; -import it.unimi.dsi.fastutil.longs.Long2IntLinkedOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectMap; -import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; -import it.unimi.dsi.fastutil.longs.LongArrayList; -import it.unimi.dsi.fastutil.longs.LongIterator; +import it.unimi.dsi.fastutil.longs.*; import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet; +import it.unimi.dsi.fastutil.objects.ObjectSortedSet; +import it.unimi.dsi.fastutil.objects.ObjectSortedSets; import it.unimi.dsi.fastutil.objects.ReferenceLinkedOpenHashSet; import net.minecraft.nbt.CompoundTag; import io.papermc.paper.chunk.system.ChunkSystem; @@ -39,13 +35,8 @@ import org.bukkit.plugin.Plugin; import org.slf4j.Logger; import java.io.IOException; import java.text.DecimalFormat; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; +import java.util.*; +import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -67,16 +58,16 @@ public final class ChunkHolderManager { final ReentrantLock ticketLock = new ReentrantLock(); private final SWMRLong2ObjectHashTable chunkHolders = new SWMRLong2ObjectHashTable<>(16384, 0.25f); - private final Long2ObjectOpenHashMap>> tickets = new Long2ObjectOpenHashMap<>(8192, 0.25f); + private final Long2ObjectMap>> tickets = Long2ObjectMaps.synchronize(new Long2ObjectOpenHashMap<>(8192, 0.25f)); // what a disaster of a name // this is a map of removal tick to a map of chunks and the number of tickets a chunk has that are to expire that tick - private final Long2ObjectOpenHashMap removeTickToChunkExpireTicketCount = new Long2ObjectOpenHashMap<>(); + private final Long2ObjectMap removeTickToChunkExpireTicketCount = Long2ObjectMaps.synchronize(new Long2ObjectOpenHashMap<>()); private final ServerLevel world; private final ChunkTaskScheduler taskScheduler; private long currentTick; - private final ArrayDeque pendingFullLoadUpdate = new ArrayDeque<>(); - private final ObjectRBTreeSet autoSaveQueue = new ObjectRBTreeSet<>((final NewChunkHolder c1, final NewChunkHolder c2) -> { + private final Deque pendingFullLoadUpdate = new ConcurrentLinkedDeque<>(); + private final ObjectSortedSet autoSaveQueue = ObjectSortedSets.synchronize(new ObjectRBTreeSet<>((final NewChunkHolder c1, final NewChunkHolder c2) -> { if (c1 == c2) { return 0; } @@ -95,7 +86,7 @@ public final class ChunkHolderManager { } return Long.compare(coord1, coord2); - }); + })); public ChunkHolderManager(final ServerLevel world, final ChunkTaskScheduler taskScheduler) { this.world = world; @@ -311,7 +302,7 @@ public final class ChunkHolderManager { public Long2ObjectOpenHashMap>> getTicketsCopy() { this.ticketLock.lock(); try { - return this.tickets.clone(); + return new Long2ObjectOpenHashMap<>(this.tickets); } finally { this.ticketLock.unlock(); } @@ -784,7 +775,7 @@ public final class ChunkHolderManager { } if (!TickThread.isTickThread()) { this.taskScheduler.scheduleChunkTask(() -> { - final ArrayDeque pendingFullLoadUpdate = ChunkHolderManager.this.pendingFullLoadUpdate; + final Deque pendingFullLoadUpdate = ChunkHolderManager.this.pendingFullLoadUpdate; for (int i = 0, len = changedFullStatus.size(); i < len; ++i) { pendingFullLoadUpdate.add(changedFullStatus.get(i)); } @@ -792,7 +783,7 @@ public final class ChunkHolderManager { ChunkHolderManager.this.processPendingFullUpdate(); }, PrioritisedExecutor.Priority.HIGHEST); } else { - final ArrayDeque pendingFullLoadUpdate = this.pendingFullLoadUpdate; + final Deque pendingFullLoadUpdate = this.pendingFullLoadUpdate; for (int i = 0, len = changedFullStatus.size(); i < len; ++i) { pendingFullLoadUpdate.add(changedFullStatus.get(i)); } @@ -1039,7 +1030,7 @@ public final class ChunkHolderManager { // only call on tick thread protected final boolean processPendingFullUpdate() { - final ArrayDeque pendingFullLoadUpdate = this.pendingFullLoadUpdate; + final Deque pendingFullLoadUpdate = this.pendingFullLoadUpdate; boolean ret = false;