From c1a4cadfdb29a3f8b016eb705fd0835f5581f194 Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:25:44 -0600 Subject: [PATCH] fix(core): wait for the sweep worker thread to exit on shutdown (#9639) --- .../io/floci/aws/core/common/SweepWorker.java | 37 +++-- .../common/SweepWorkerTerminationTest.java | 129 ++++++++++++++++++ 2 files changed, 158 insertions(+), 8 deletions(-) create mode 100644 src/test/java/io/floci/aws/core/common/SweepWorkerTerminationTest.java diff --git a/src/main/java/io/floci/aws/core/common/SweepWorker.java b/src/main/java/io/floci/aws/core/common/SweepWorker.java index dcf2318093..0d39bd46b7 100644 --- a/src/main/java/io/floci/aws/core/common/SweepWorker.java +++ b/src/main/java/io/floci/aws/core/common/SweepWorker.java @@ -2,9 +2,11 @@ package io.floci.aws.core.common; import org.jboss.logging.Logger; +import java.time.Duration; import java.time.Instant; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; @@ -15,14 +17,17 @@ import java.util.function.Consumer; */ public final class SweepWorker { private static final Logger LOG = Logger.getLogger(SweepWorker.class); + private static final Duration SHUTDOWN_TIMEOUT = Duration.ofSeconds(5); private final String name; private final Consumer sweep; private final long intervalSeconds; private final boolean sweepAtStart; + private final long shutdownTimeoutNanos; private final ScheduledExecutorService executor; private final ReentrantLock sweepLock = new ReentrantLock(); private volatile boolean paused; + private volatile Thread workerThread; /** * @param name display name used in the thread name and log messages @@ -33,16 +38,22 @@ public final class SweepWorker { */ public SweepWorker(String name, boolean enabled, long intervalSeconds, boolean sweepAtStart, Consumer sweep) { + this(name, intervalSeconds, sweepAtStart, sweep, + enabled ? Thread.ofPlatform().name(name).daemon(true).factory() : null, SHUTDOWN_TIMEOUT); + } + + SweepWorker(String name, long intervalSeconds, boolean sweepAtStart, Consumer sweep, + ThreadFactory threadFactory, Duration shutdownTimeout) { this.name = name; this.sweep = sweep; this.intervalSeconds = Math.max(1, intervalSeconds); this.sweepAtStart = sweepAtStart; - this.executor = enabled - ? Executors.newSingleThreadScheduledExecutor(task -> { - Thread thread = new Thread(task, name); - thread.setDaemon(true); - return thread; - }) : null; + this.shutdownTimeoutNanos = shutdownTimeout.toNanos(); + this.executor = threadFactory == null ? null : Executors.newSingleThreadScheduledExecutor(task -> { + Thread thread = threadFactory.newThread(task); + workerThread = thread; + return thread; + }); } public void start() { @@ -51,14 +62,24 @@ public final class SweepWorker { } } - /** Interrupts a running sweep and waits briefly for it to end. */ + /** Interrupts a running sweep and waits up to five seconds for its worker thread to exit. */ public void stop() { if (executor == null) { return; } + long deadline = System.nanoTime() + shutdownTimeoutNanos; executor.shutdownNow(); + if (workerThread == Thread.currentThread()) { + return; + } try { - if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + boolean terminated = executor.awaitTermination(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); + Thread thread = workerThread; + if (terminated && thread != null) { + // The executor signals termination before its worker returns from Thread.run(). + TimeUnit.NANOSECONDS.timedJoin(thread, deadline - System.nanoTime()); + } + if (!terminated || (thread != null && thread.isAlive())) { LOG.warnv("The {0} worker is still finishing a sweep during shutdown", name); } } catch (InterruptedException e) { diff --git a/src/test/java/io/floci/aws/core/common/SweepWorkerTerminationTest.java b/src/test/java/io/floci/aws/core/common/SweepWorkerTerminationTest.java new file mode 100644 index 0000000000..cedf7a95c7 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/SweepWorkerTerminationTest.java @@ -0,0 +1,129 @@ +package io.floci.aws.core.common; + +import io.floci.aws.testing.ThreadStates; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.time.Duration; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; + +@Timeout(20) +class SweepWorkerTerminationTest { + @Test + void stopWaitsForTheWorkerToExitAfterTheExecutorTerminates() throws Exception { + AtomicReference owner = new AtomicReference<>(); + CountDownLatch executorExited = new CountDownLatch(1); + CountDownLatch releaseThread = new CountDownLatch(1); + AtomicReference workerThread = new AtomicReference<>(); + ThreadFactory factory = task -> { + Thread thread = Thread.ofPlatform().daemon(true).unstarted(() -> { + try { + task.run(); + } finally { + Thread.interrupted(); // shutdownNow may have interrupted this thread. + executorExited.countDown(); + awaitRelease(releaseThread); + } + }); + workerThread.set(thread); + return thread; + }; + SweepWorker worker = new SweepWorker("sweep-tail", 3600, true, now -> owner.get().stop(), + factory, Duration.ofSeconds(5)); + owner.set(worker); + Thread caller = Thread.ofPlatform().unstarted(worker::stop); + try { + worker.start(); + assertTrue(executorExited.await(5, TimeUnit.SECONDS)); + caller.start(); + assertEquals(Thread.State.TIMED_WAITING, ThreadStates.awaitState(caller, + Set.of(Thread.State.TIMED_WAITING, Thread.State.TERMINATED), Duration.ofSeconds(5), + "caller joining the worker thread")); + releaseThread.countDown(); + assertTrue(caller.join(Duration.ofSeconds(5))); + assertFalse(workerThread.get().isAlive()); + } finally { + releaseThread.countDown(); + worker.stop(); + } + } + + @Test + void stopReturnsWithinItsBudgetWhenTheSweepIgnoresInterruption() throws Exception { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicReference workerThread = new AtomicReference<>(); + SweepWorker worker = new SweepWorker("uncooperative-sweep", 3600, true, now -> { + workerThread.set(Thread.currentThread()); + entered.countDown(); + awaitRelease(release); + }, Thread.ofPlatform().daemon(true).factory(), Duration.ofMillis(25)); + try (ExecutorService caller = Executors.newSingleThreadExecutor()) { + try { + worker.start(); + assertTrue(entered.await(5, TimeUnit.SECONDS)); + caller.submit(worker::stop).get(2, TimeUnit.SECONDS); + assertTrue(workerThread.get().isAlive()); + } finally { + release.countDown(); + worker.stop(); + } + } + } + + @Test + void aSweepCanStopItsOwnWorker() throws Exception { + AtomicReference owner = new AtomicReference<>(); + CountDownLatch stopped = new CountDownLatch(1); + SweepWorker worker = new SweepWorker("self-stopping-sweep", true, 3600, true, now -> { + owner.get().stop(); + stopped.countDown(); + }); + owner.set(worker); + try { + worker.start(); + assertTrue(stopped.await(3, TimeUnit.SECONDS)); + } finally { + worker.stop(); + } + } + + @Test + void stopPreservesTheCallersInterruptFlag() throws Exception { + CountDownLatch entered = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + SweepWorker worker = new SweepWorker("interrupted-caller", true, 3600, true, now -> { + entered.countDown(); + awaitRelease(release); + }); + try { + worker.start(); + assertTrue(entered.await(5, TimeUnit.SECONDS)); + Thread.currentThread().interrupt(); + worker.stop(); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + Thread.interrupted(); + release.countDown(); + worker.stop(); + } + } + + private static void awaitRelease(CountDownLatch release) { + while (release.getCount() > 0) { + try { + release.await(); + } catch (InterruptedException ignored) { + // Only the test releases this worker, even after shutdown interrupts it. + } + } + } +}