Optimize minion removal by only acquiring writelock if we need it

This commit is contained in:
TomTom 2024-08-02 16:30:46 +02:00
parent 80127bbae9
commit faea733a55

View File

@ -103,16 +103,19 @@ public final class MinionArea {
int chunkX = (int) Math.floor(location.getX()) >> 4; int chunkX = (int) Math.floor(location.getX()) >> 4;
int chunkZ = (int) Math.floor(location.getZ()) >> 4; int chunkZ = (int) Math.floor(location.getZ()) >> 4;
this.writeLock.lock(); // Load the list into stack memory for faster access
ObjectArrayList<ChunkPos> positions = this.positions;
boolean needsWrite = false;
this.readLock.lock();
try { try {
this.writeCount++; this.readCount++;
// Load the list into stack memory for faster access
ObjectArrayList<ChunkPos> positions = this.positions;
ObjectListIterator<ChunkPos> positionIterator = positions.iterator(); ObjectListIterator<ChunkPos> positionIterator = positions.iterator();
while (positionIterator.hasNext()) { while (positionIterator.hasNext()) {
ChunkPos nextPos = positionIterator.next(); ChunkPos nextPos = positionIterator.next();
if (nextPos.x() == chunkX && nextPos.z() == chunkZ) { if (nextPos.x() == chunkX && nextPos.z() == chunkZ) {
if (nextPos.removeMinion(minion)) { if (nextPos.removeMinion(minion)) {
needsWrite = true;
positionIterator.remove(); positionIterator.remove();
} }
@ -120,7 +123,24 @@ public final class MinionArea {
} }
} }
} finally { } finally {
this.writeLock.unlock(); this.readLock.unlock();
}
if (needsWrite) {
this.writeLock.lock();
try {
this.writeCount++;
ObjectListIterator<ChunkPos> positionIterator = positions.iterator();
while (positionIterator.hasNext()) {
ChunkPos nextPos = positionIterator.next();
if (nextPos.x() == chunkX && nextPos.z() == chunkZ) {
positionIterator.remove();
break;
}
}
} finally {
this.writeLock.unlock();
}
} }
} }