GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — SingleThreadEventExecutor: do not start threads when shutting down never-used executors by arimu1 · Pull Request #17183 · netty/netty

SingleThreadEventExecutor: do not start threads when shutting down never-used executors #17183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
arimu1 wants to merge 13 commits into netty:4.2 from arimu1:fix/17135-shutdown-unstarted-threads

Uh oh!

There was an error while loading. Please reload this page.

Closed

SingleThreadEventExecutor: do not start threads when shutting down never-used executors #17183

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
13 commits
Select commit Hold shift + click to select a range
fb206da
SingleThreadEventExecutor: skip thread start on unused shutdown
arimu1 Aug 1, 2026
59c7f47
chore: re-trigger CI after environmental OOM/KQueue failures
arimu1 Aug 2, 2026
2aa4f08
SingleThreadEventExecutor: fix never-started shutdown for IoEventLoop
arimu1 Aug 3, 2026
a9a6d4a
Document never-started group quiet-period tradeoff for #17135
arimu1 Aug 4, 2026
d0ed2ad
SingleThreadEventExecutor: honor quiet period for never-started children
arimu1 Aug 4, 2026
8186b96
IoUringIoHandler: destroy never-initialized rings without io_uring_enter
arimu1 Aug 12, 2026
4494123
Address review: drop MultithreadEventExecutorGroup hunk; remove unuse…
arimu1 Aug 12, 2026
3373ed5
SingleThreadEventExecutor: fix execute/suspend race stranding tasks
arimu1 Aug 21, 2026
c719d82
SingleThreadEventExecutor: restart worker after suspend wind-down if …
arimu1 Aug 21, 2026
5c5bf0f
Merge branch '4.2' into fix/17135-shutdown-unstarted-threads
normanmaurer Aug 25, 2026
68879cd
Merge branch '4.2' into fix/17135-shutdown-unstarted-threads
arimu1 Oct 3, 2026
fae4cca
SingleThreadEventExecutor: reject tasks that race never-started termi…
arimu1 Oct 3, 2026
378d158
Merge branch '4.2' into fix/17135-shutdown-unstarted-threads
chrisvest Oct 19, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

245 changes: 233 additions & 12 deletions 245 common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java
Show comments Show annotations
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
Expand Down Expand Up @@ -97,6 +98,12 @@
private final Lock processingLock = new ReentrantLock();
private final CountDownLatch threadLock = new CountDownLatch(1);
private final Set<Runnable> shutdownHooks = new LinkedHashSet<Runnable>();
/**
* Ensures at most one worker start is issued for this executor (including the
* never-started → SHUTTING_DOWN path that must start a thread only if a task arrives
* during the quiet period).
*/
private final AtomicBoolean threadStartIssued = new AtomicBoolean();
private final boolean addTaskWakesUp;
private final int maxPendingTasks;
private final RejectedExecutionHandler rejectedExecutionHandler;
Expand Down Expand Up @@ -128,6 +135,13 @@

private final Promise<?> terminationFuture = new DefaultPromise<Void>(GlobalEventExecutor.INSTANCE);

private final Runnable neverStartedQuietPeriodTask = new Runnable() {
@Override
public void run() {
onNeverStartedQuietPeriodTimer();
}
};

/**
* Create a new instance
*
Expand Down Expand Up @@ -363,7 +377,7 @@
if (scheduledTaskQueue == null || scheduledTaskQueue.isEmpty()) {
return false;
}
long nanoTime = getCurrentTimeNanos();

Check warning on line 380 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / verify-pr

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 380 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / windows-x86_64-java11-boringssl

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 380 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / Analyze (cpp)

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 380 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / Analyze (java)

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 380 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / macos-aarch64-java11-boringssl build

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 380 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / macos-x86_64-java11-boringssl build

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
Runnable scheduledTask = pollScheduledTask(nanoTime);
if (scheduledTask == null) {
return false;
Expand Down Expand Up @@ -440,7 +454,7 @@
} while (!fetchedAll); // keep on processing until we fetched all scheduled tasks.

if (ranAtLeastOne) {
lastExecutionTime = getCurrentTimeNanos();

Check warning on line 457 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / verify-pr

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 457 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / windows-x86_64-java11-boringssl

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 457 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / Analyze (cpp)

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 457 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / Analyze (java)

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 457 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / macos-aarch64-java11-boringssl build

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 457 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / macos-x86_64-java11-boringssl build

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
}
afterRunningAllTasks();
return ranAtLeastOne;
Expand All @@ -465,7 +479,7 @@
} while (ranAtLeastOneTask && ++drainAttempt < maxDrainAttempts);

if (drainAttempt > 0) {
lastExecutionTime = getCurrentTimeNanos();

Check warning on line 482 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / verify-pr

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 482 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / windows-x86_64-java11-boringssl

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 482 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / Analyze (cpp)

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 482 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / Analyze (java)

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 482 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / macos-aarch64-java11-boringssl build

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated

Check warning on line 482 in common/src/main/java/io/netty/util/concurrent/SingleThreadEventExecutor.java

View workflow job for this annotation

GitHub Actions / macos-x86_64-java11-boringssl build

[deprecation] getCurrentTimeNanos() in AbstractScheduledEventExecutor has been deprecated
}
afterRunningAllTasks();

Expand Down Expand Up @@ -1158,27 +1172,69 @@
resetBusyCycles();
boolean success = false;
try {
doStartThread();
issueDoStartThread();
success = true;
// execute() may have moved ST_SUSPENDED -> ST_STARTED while this thread is still
// winding down; wake it so it re-engages instead of exiting with no replacement.
if (currentState == ST_SUSPENDED && thread != null) {
wakeup(false);
}
} finally {
if (!success) {
STATE_UPDATER.compareAndSet(this, ST_STARTED, ST_NOT_STARTED);
threadStartIssued.set(false);
}
}
break;
}
// The state changed after we read it. If trySuspend() moved it from ST_NOT_STARTED to ST_SUSPENDED no
// thread was started, so we need to try again. Otherwise the task that was just added might never run.
// This may deliberately un-suspend an executor that trySuspend() has just suspended, which is the same
// thing execute() does for an executor that is already suspended. We only loop again if another thread
// changed the state in between, so this can't spin.
// The state changed after we read it. If trySuspend() moved it from ST_NOT_STARTED to
// ST_SUSPENDED no thread was started, so we need to try again. Otherwise the task that
// was just added might never run. This may deliberately un-suspend an executor that
// trySuspend() has just suspended, which is the same thing execute() does for an
// executor that is already suspended. We only loop again if another thread changed the
// state in between, so this can't spin.
currentState = state;
}
if (currentState == ST_SHUTTING_DOWN && thread == null) {
// Never-started executor already in graceful shutdown: a task arrived during the
// quiet period. Start a worker without changing state away from SHUTTING_DOWN so
// confirmShutdown still honors quietPeriod/timeout (#17135 + quiet-period accept).
// A successful start above breaks with currentState still NOT_STARTED or SUSPENDED,
// so this branch does not also run.
try {
issueDoStartThread();
} catch (Throwable cause) {
STATE_UPDATER.set(this, ST_TERMINATED);
terminationFuture.tryFailure(cause);
if (!(cause instanceof Exception)) {
PlatformDependent.throwException(cause);
}
}
}
}

private boolean ensureThreadStarted(int oldState) {
// Never-started shutdown (#17135):
// - quietPeriod == 0: terminate immediately without creating a worker.
// - quietPeriod > 0: stay SHUTTING_DOWN without a worker; schedule a timer to
// terminate when the quiet period elapses with no tasks. execute() during that
// window starts a worker via startThread() (ST_SHUTTING_DOWN + thread == null).
if (oldState == ST_NOT_STARTED) {
if (gracefulShutdownQuietPeriod == 0) {
if (tryTerminateIfNeverStarted()) {
return true;
}
} else {
scheduleNeverStartedQuietPeriodExpire();
return true;
}
}

if (oldState == ST_NOT_STARTED || oldState == ST_SUSPENDED) {
try {
// Not gated by threadStartIssued. A worker that is still winding down may hold
// that flag; skipping here would leave shutdown waiting for a thread that never
// starts. processingLock serializes the two runnables.
doStartThread();
} catch (Throwable cause) {
STATE_UPDATER.set(this, ST_TERMINATED);
Expand All @@ -1194,6 +1250,156 @@
return false;
}

/**
* Issue at most one {@link #doStartThread()} for this executor.
*/
private void issueDoStartThread() {
if (!threadStartIssued.compareAndSet(false, true)) {
return;
}
try {
doStartThread();
} catch (Throwable t) {
threadStartIssued.set(false);
PlatformDependent.throwException(t);
}
}

/**
* Schedule termination (or late worker start if work appears) for a never-started
* executor that entered {@link #ST_SHUTTING_DOWN} with a non-zero quiet period.
*/
private void scheduleNeverStartedQuietPeriodExpire() {
if (gracefulShutdownStartTime == 0) {
gracefulShutdownStartTime = getCurrentTimeNanos();
}
// Treat "no tasks yet" as last activity at shutdown start so quiet-period math matches
// confirmShutdown when a worker is started later.
lastExecutionTime = gracefulShutdownStartTime;

final long quietNanos = gracefulShutdownQuietPeriod;
final long timeoutNanos = gracefulShutdownTimeout;
// Fire at quiet-period end (and again at timeout if longer) so we still terminate if
// the first timer races with a late execute that then drains before the second fire.
GlobalEventExecutor.INSTANCE.schedule(neverStartedQuietPeriodTask, quietNanos, TimeUnit.NANOSECONDS);
if (timeoutNanos > quietNanos) {
GlobalEventExecutor.INSTANCE.schedule(neverStartedQuietPeriodTask, timeoutNanos, TimeUnit.NANOSECONDS);
}
}

private void onNeverStartedQuietPeriodTimer() {
if (thread != null || isTerminated() || !isShuttingDown()) {
return;
}
// Work pending → start worker under SHUTTING_DOWN so confirmShutdown drains it.
if (!taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty()) {
startThread();
return;
}
if (tryTerminateIfNeverStarted()) {
return;
}
// Race: work appeared after empty check.
startThread();
}

/**
* If this executor was never started and has no pending work, transition straight to
* {@link #ST_TERMINATED} without creating a thread.
*
* @return {@code true} if the caller must not start a thread: termination completed
* without a worker, or this method already issued one for work that was queued before
* {@link #ST_SHUTDOWN}. {@code false} if the caller should start a thread.
*/
private boolean tryTerminateIfNeverStarted() {
// Try to take the processing lock so we do not race with a just-started worker thread.
Comment thread

@allthingssecurity allthingssecurity Sep 29, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lock only protects against a worker that already holds it. A worker issued while this method runs waits on
processingLock.lock() (:1360), and it runs right after we release the lock, with the state already
ST_TERMINATED.

Claude Code on behalf of allthingssecurity

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
// If the lock is held, a thread is (or will be) running — fall back to the normal path.
if (!processingLock.tryLock()) {
return false;
}
boolean claimedStart = false;
boolean keepClaim = false;
try {
if (thread != null || hasPendingWork()) {
return false;
}
// issueDoStartThread() and this termination must exclude each other. A worker that
// already passed the gate is waiting on processingLock; do not terminate under it.
if (!threadStartIssued.compareAndSet(false, true)) {
return false;
}
claimedStart = true;

for (;;) {
int currentState = state;
if (currentState >= ST_TERMINATED) {
keepClaim = true;
return true;
}
if (currentState < ST_SHUTTING_DOWN) {
// Unexpected: state moved backwards from shutting down. Fall back.
return false;
}
if (hasPendingWork()) {
return false;
}
// SHUTTING_DOWN still accepts tasks. Publish SHUTDOWN before the last emptiness
// check so an execute() in that window is rejected instead of queued and then
// discarded by drainTasks(), which also used to let a worker run after cleanup().
if (currentState == ST_SHUTTING_DOWN) {
if (!STATE_UPDATER.compareAndSet(this, ST_SHUTTING_DOWN, ST_SHUTDOWN)) {
continue;
}
currentState = ST_SHUTDOWN;
}
if (hasPendingWork()) {
// Accepted before ST_SHUTDOWN. startThread() will not start a worker once the
// state has left SHUTTING_DOWN, so issue one here.
threadStartIssued.set(false);
claimedStart = false;
issueDoStartThread();
keepClaim = true;
return true;
}
if (STATE_UPDATER.compareAndSet(this, currentState, ST_TERMINATED)) {
Comment thread

@allthingssecurity allthingssecurity Sep 29, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An execute() that runs between the check above and this CAS gets lost. addTask succeeds. startThread() takes
the ST_SHUTTING_DOWN && thread == null branch and issues a worker, which blocks on processingLock.
isShutdown() is still false, so the task is not rejected. After the CAS, drainTasks() below discards it, and the
blocked worker then enters run() on the terminated executor. Deterministic reproducer and numbers are in the
review body.

Claude Code on behalf of allthingssecurity

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
keepClaim = true;
try {
// Subclass cleanup (e.g. SingleThreadIoEventLoop) may assert
// inEventLoop() and must still destroy constructor-created
// resources (IoHandler / native FDs). Bind the current thread
// as the event-loop thread only for cleanup; run() never ran
// so there is no concurrent event-loop activity.
assert thread == null;
thread = Thread.currentThread();
try {
cleanup();
} finally {
thread = null;
}
} finally {
threadLock.countDown();
int numUserTasks = drainTasks();
if (numUserTasks > 0 && logger.isWarnEnabled()) {
logger.warn("An event executor terminated with " +
"non-empty task queue (" + numUserTasks + ')');
}
terminationFuture.setSuccess(null);
}
return true;
}
}
} finally {
if (claimedStart && !keepClaim) {
threadStartIssued.set(false);
}
processingLock.unlock();
}
}

private boolean hasPendingWork() {
return !taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty();
}

private void doStartThread() {
executor.execute(new Runnable() {
@Override
Expand Down Expand Up @@ -1226,10 +1432,11 @@
continue;
}

if (!canSuspend(ST_SUSPENDED) && STATE_UPDATER.compareAndSet(SingleThreadEventExecutor.this,
ST_SUSPENDED, ST_STARTED)) {
// Seems like there was something added to the task queue again in the meantime but we
// were able to re-engage this thread as the event loop thread.
if (!canSuspend(ST_SUSPENDED)) {
// Work arrived while suspending. execute() may already have moved us to
// ST_STARTED; re-engage this thread in either case.
STATE_UPDATER.compareAndSet(SingleThreadEventExecutor.this,
ST_SUSPENDED, ST_STARTED);
continue;
}
suspend = true;
Expand Down Expand Up @@ -1268,10 +1475,12 @@
}

try {
if (shutdown) {
if (shutdown && state != ST_TERMINATED) {
// Run all remaining tasks and shutdown hooks. At this point the event loop
// is in ST_SHUTTING_DOWN state still accepting tasks which is needed for
// graceful shutdown with quietPeriod.
// A second worker can be inside doStartThread() after the first already
// published ST_TERMINATED; it must not complete the future again.
for (;;) {
if (confirmShutdown()) {
break;
Expand All @@ -1294,7 +1503,7 @@
}
} finally {
try {
if (shutdown) {
if (shutdown && state != ST_TERMINATED) {
try {
cleanup();
} finally {
Expand Down Expand Up @@ -1326,8 +1535,20 @@
}
} finally {
thread = null;
// Allow a later startThread()/issueDoStartThread() after suspension or
// termination of this worker (suspension reuses the same executor).
threadStartIssued.set(false);
// Let the next thread take over if needed.
processingLock.unlock();
// execute() or shutdown may have moved us to ST_STARTED / SHUTTING_DOWN
// while this thread still held threadStartIssued (e.g. during removeAll).
int currentState = state;
if (currentState == ST_STARTED
|| (currentState >= ST_SHUTTING_DOWN && currentState < ST_TERMINATED)) {
// Direct start: issueDoStartThread() would no-op if this winding-down
// worker had not cleared the gate yet, or if a racer still holds it.
doStartThread();
}
}
}
}
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.