From afb14bc1f654d79476b507c2d52cad4c88a28ae3 Mon Sep 17 00:00:00 2001 From: Jozufozu Date: Sat, 27 May 2023 12:01:47 -0700 Subject: [PATCH] Hol up - Spin wait for .01ms in WorkerThreads before waiting --- .../backend/task/ParallelTaskExecutor.java | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/jozufozu/flywheel/backend/task/ParallelTaskExecutor.java b/src/main/java/com/jozufozu/flywheel/backend/task/ParallelTaskExecutor.java index f243f2149..2661c1313 100644 --- a/src/main/java/com/jozufozu/flywheel/backend/task/ParallelTaskExecutor.java +++ b/src/main/java/com/jozufozu/flywheel/backend/task/ParallelTaskExecutor.java @@ -198,7 +198,6 @@ public class ParallelTaskExecutor implements TaskExecutor { } private class WorkerThread extends Thread { - public WorkerThread(String name) { super(name); } @@ -209,14 +208,28 @@ public class ParallelTaskExecutor implements TaskExecutor { while (ParallelTaskExecutor.this.running.get()) { Runnable task = taskQueue.pollFirst(); - if (task == null) { + if (task != null) { + processTask(task); + } else { // Nothing to do, time to sleep. - taskNotifier.awaitNotification(); - continue; + spinThenWait(); + } + } + } + + private void spinThenWait() { + var waitStart = System.nanoTime(); + + // Spin for .01ms before waiting to reduce latency in narrow conditions. + while (System.nanoTime() - waitStart < 10_000) { + if (!taskQueue.isEmpty()) { + // Nice! Exit without waiting. + return; } - processTask(task); + Thread.onSpinWait(); } + taskNotifier.awaitNotification(); } } }