From 3199b77ae5d5e4af7a15dfd5b9be5626c9ac80d9 Mon Sep 17 00:00:00 2001 From: mcrcortex <18544518+MCRcortex@users.noreply.github.com> Date: Sat, 12 Jul 2025 14:12:06 +1000 Subject: [PATCH] Reorder operations in attempt to fix race conditions --- .../cortex/voxy/common/thread/ServiceSlice.java | 3 ++- .../voxy/common/thread/ServiceThreadPool.java | 17 ++++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/me/cortex/voxy/common/thread/ServiceSlice.java b/src/main/java/me/cortex/voxy/common/thread/ServiceSlice.java index 846e7476..44809323 100644 --- a/src/main/java/me/cortex/voxy/common/thread/ServiceSlice.java +++ b/src/main/java/me/cortex/voxy/common/thread/ServiceSlice.java @@ -96,9 +96,10 @@ public class ServiceSlice extends TrackedObject { Logger.error("Tried to do work on a dead service: " + this.name, new Throwable()); return; } + this.threadPool.addWeight(this); this.jobCount2.incrementAndGet(); this.jobCount.release(); - this.threadPool.execute(this); + this.threadPool.execute(); } public void shutdown() { diff --git a/src/main/java/me/cortex/voxy/common/thread/ServiceThreadPool.java b/src/main/java/me/cortex/voxy/common/thread/ServiceThreadPool.java index cc96ee5a..f754ec2a 100644 --- a/src/main/java/me/cortex/voxy/common/thread/ServiceThreadPool.java +++ b/src/main/java/me/cortex/voxy/common/thread/ServiceThreadPool.java @@ -137,8 +137,11 @@ public class ServiceThreadPool { this.serviceSlices = newArr; } - void execute(ServiceSlice service) { - this.totalJobWeight.addAndGet(service.weightPerJob); + long addWeight(ServiceSlice service) { + return this.totalJobWeight.addAndGet(service.weightPerJob); + } + + void execute() { this.jobCounter.release(1); } @@ -268,7 +271,15 @@ public class ServiceThreadPool { //Consumed a job from the service, decrease weight by the amount if (this.totalJobWeight.addAndGet(-service.weightPerJob)<0) { - throw new IllegalStateException("Total job weight is negative"); + Logger.error("Total job weight is negative"); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + if (this.totalJobWeight.get()<0) { + throw new IllegalStateException("Total job weight still negative"); + } } //Sleep for a bit after running a job, yeild the thread