Fix tick thread not being properly terminated

This commit is contained in:
TheMode 2021-04-15 04:06:55 +02:00
parent b3a548287a
commit f4ee5505ca
4 changed files with 26 additions and 17 deletions

View File

@ -251,6 +251,7 @@ public final class UpdateManager {
* Stops the server loop.
*/
public void stop() {
stopRequested = true;
this.stopRequested = true;
this.threadProvider.shutdown();
}
}

View File

@ -105,7 +105,7 @@ public interface Acquirable<T> {
}
@ApiStatus.Internal
public void refreshBatchInfo(BatchThread batchThread, Chunk batchChunk) {
public void refreshBatchInfo(@NotNull BatchThread batchThread, @NotNull Chunk batchChunk) {
this.batchThread = batchThread;
this.batchChunk = batchChunk;
}

View File

@ -34,7 +34,10 @@ public class BatchThread extends Thread {
}
public void shutdown() {
this.runnable.stop = true;
synchronized (runnable.tickLock) {
this.runnable.stop = true;
this.runnable.tickLock.notifyAll();
}
}
public static class BatchRunnable implements Runnable {
@ -79,6 +82,10 @@ public class BatchThread extends Thread {
// Wait for the next notify (game tick)
try {
if (stop) {
break;
}
this.tickLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
@ -91,7 +98,7 @@ public class BatchThread extends Thread {
this.countDownLatch = countDownLatch;
this.queue.add(runnable);
synchronized (tickLock) {
this.tickLock.notify();
this.tickLock.notifyAll();
}
}

View File

@ -92,6 +92,7 @@ public abstract class ThreadProvider {
for (BatchThread thread : threads) {
final var chunkEntries = threadChunkMap.get(thread);
if (chunkEntries == null) {
// The thread never had any task
countDownLatch.countDown();
continue;
}
@ -115,21 +116,22 @@ public abstract class ThreadProvider {
}
public synchronized void refreshThreads() {
// Clear removed entities
for (Entity entity : removedEntities) {
Acquirable<Entity> acquirable = entity.getAcquiredElement();
Chunk batchChunk = acquirable.getHandler().getBatchChunk();
{
for (Entity entity : removedEntities) {
Acquirable<Entity> acquirable = entity.getAcquiredElement();
Chunk batchChunk = acquirable.getHandler().getBatchChunk();
// Remove from list
{
ChunkEntry chunkEntry = chunkEntryMap.get(batchChunk);
if (chunkEntry != null) {
chunkEntry.entities.remove(entity);
// Remove from list
{
ChunkEntry chunkEntry = chunkEntryMap.get(batchChunk);
if (chunkEntry != null) {
chunkEntry.entities.remove(entity);
}
}
}
this.removedEntities.clear();
}
this.removedEntities.clear();
// Update as many entities as possible
// TODO: incremental update instead of full
@ -163,7 +165,7 @@ public abstract class ThreadProvider {
}
}
public void removeEntity(Entity entity) {
public void removeEntity(@NotNull Entity entity) {
this.removedEntities.add(entity);
}
@ -171,8 +173,7 @@ public abstract class ThreadProvider {
this.threads.forEach(BatchThread::shutdown);
}
@NotNull
public List<BatchThread> getThreads() {
public @NotNull List<@NotNull BatchThread> getThreads() {
return threads;
}