Repository navigation
Conversation
|
Local verification (Temurin 21): CI failures on this run look environmental rather than regressions of #17135:
Happy to re-run CI / dig further if maintainers see a real regression path. |
|
@arimu1 there are multiple test failures... please check and let me know once you fixed these |
|
@normanmaurer Thanks — dug into the TestLens / CI failures. They were real regressions from this PR, not only env OOM. Root cause
That hit every IoEventLoop suite that shuts down never-started children (KQueue, Nio, Fix (latest push)
Local verification (Temurin 21)
Rebased onto latest |
f4286c9 to
d515a51
Compare
|
From scrolling through the changes, it is not clear to me if this situation is handled correctly: EventLoopGroup group = new MultiThreadIoEventLoopGroup(300, NioIoHandler.newFactory());
group.shutdownGracefully(100, 100, TimeUnit.MILLISECONDS);
Thread.sleep(10); // Wait for threads to transition directly to terminated
group.execute(...); // Within grace period so should be executedI may be misunderstanding how the grace period is intended to work or missed something. |
|
@mega12345mega Good catch — that scenario is handled by design for #17135, not by accepting late tasks on never-started children. What happens with your snippetEventLoopGroup group = new MultiThreadIoEventLoopGroup(300, NioIoHandler.newFactory());
group.shutdownGracefully(100, 100, TimeUnit.MILLISECONDS);
Thread.sleep(10);
group.execute(...);
Why not honor the caller's 100ms quiet period on unused children?Accepting tasks during the quiet period requires a running event-loop thread. Starting all 300 workers on shutdown is exactly what this PR avoids. Already-started children still get the full Single-executor pathA lone Docs + testPushed javadoc on If maintainers prefer that non-zero group quiet periods still start never-used children so late |
|
The concern is for the case where none of the threads in a Thread is running beforehand: Thread isn't running and doesn't receive task: Thread isn't running and does receive task: |
Never-started executors with a non-zero quiet period stay SHUTTING_DOWN without starting a worker, schedule a GlobalEventExecutor timer to terminate when quiet elapses with no work, and start a worker only if execute() arrives during the quiet period. MultithreadEventExecutorGroup no longer forces quietPeriod=0 on unused children. Addresses mega12345mega's design feedback on netty#17183 / netty#17135. Signed-off-by: arimu1 <[email protected]>
|
@mega12345mega Implemented the design you sketched for never-started + quiet period:
Tests:
|
|
@arimu1 did you sign our icla yet ? https://netty.io/s/icla |
| // Pass the caller's quietPeriod/timeout to every child, including never-started | ||
| // ones (#17135). SingleThreadEventExecutor terminates never-started children | ||
| // without creating a worker when the quiet period elapses with no tasks, and | ||
| // only starts a worker if execute() arrives during the quiet period. |
There was a problem hiding this comment.
imho all of this can be removed... and so there needs to be no changes at all to this class
|
Hi @normanmaurer — thanks for the nudge. ICLA signed. |
|
@arimu1 please check the test-failures |
SingleThreadEventExecutor.tryTerminateIfNeverStarted() calls cleanup() off-thread before run()/initialize(). IoUring rings are created disabled; destroy()'s submission path needs enable() first, which caused io_uring_enter error -77 in IoUringEventLoopTest.shutdownBeforeStart. Skip submission-based teardown when initialize() never ran; release buffer rings and close the ring directly instead. Fixes CI failures reported on netty#17183. Signed-off-by: arimu1 <[email protected]> Co-authored-by: Cursor <[email protected]>
|
@normanmaurer Checked the TestLens failures on run 31501037046 — all linux-x86_64 Java jobs failed for the same reason in Failing tests (2 errors, 0 assertion failures)
Root cause However, This is specific to io_uring; epoll/kqueue/NIO paths do not have the enable-before-enter requirement and were unaffected. Fix (32772f7) Pushed to the branch — CI should re-run shortly. I cannot reproduce io_uring tests locally (macOS); the diagnosis is from the CI stack traces above. |
|
Follow-up after internal review of the IoUring CI fix:
IoUring never-initialized |
SingleThreadEventExecutor.tryTerminateIfNeverStarted() calls cleanup() off-thread before run()/initialize(). IoUring rings are created disabled; destroy()'s submission path needs enable() first, which caused io_uring_enter error -77 in IoUringEventLoopTest.shutdownBeforeStart. Skip submission-based teardown when initialize() never ran; release buffer rings and close the ring directly instead. Fixes CI failures reported on netty#17183. Signed-off-by: arimu1 <[email protected]>
32772f7 to
2bb0c8a
Compare
chrisvest
left a comment
There was a problem hiding this comment.
This code introduces a problem where suspension and task submission can both race, and hit an unfortunate interleaving where the existing executor thread suspends, but the task submission moves the state to ST_STARTED without actually starting a thread.
I… tried creating a test for this, which seems to catch the scenario (and pass on base 4.2), but I don't love how it looks. Maybe it can be written in a different/simpler way.
@Test
@Timeout(value = 10, unit = TimeUnit.SECONDS)
public void testExecuteRacingSuspensionDoesNotStrandExecutor() throws Exception {
final AtomicBoolean armed = new AtomicBoolean();
final AtomicInteger armedCanSuspendCalls = new AtomicInteger();
final CountDownLatch executorThreadAtReengage = new CountDownLatch(1);
final CountDownLatch externalDone = new CountDownLatch(1);
final SingleThreadEventExecutor executor = new SingleThreadEventExecutor(
null, new DefaultThreadFactory("suspend-race"), false, true,
Integer.MAX_VALUE, RejectedExecutionHandlers.reject()) {
@Override
protected void run() {
for (;;) {
if (confirmShutdown()) {
return;
}
Runnable task = takeTask();
if (task != null) {
task.run();
}
if (isSuspended()) {
// Suspension requested: return so the base class can suspend this thread.
// Note: run() intentionally does not call canSuspend() so that the only
// canSuspend(int) calls after arming are the base class' two checks.
return;
}
}
}
@Override
protected boolean canSuspend(int state) {
if (armed.get() && armedCanSuspendCalls.incrementAndGet() == 2) {
// Second armed call is the re-engage check canSuspend(ST_SUSPENDED): at this
// point the executor thread has already CAS'd the state to ST_SUSPENDED but
// has not yet reset the start gate. Let an external execute() race in now.
executorThreadAtReengage.countDown();
boolean interrupted = false;
while (externalDone.getCount() > 0) {
try {
externalDone.await();
} catch (InterruptedException e) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
return super.canSuspend(state);
}
@Override
protected void wakeup(boolean inEventLoop) {
interruptThread();
}
};
// Start the executor thread and make sure it is parked in takeTask().
LatchTask started = new LatchTask();
executor.execute(started);
started.await();
// Arm the interception, then request suspension, then wait for executor to hit suspension point.
armed.set(true);
assertTrue(executor.trySuspend());
assertTrue(executorThreadAtReengage.await(5, TimeUnit.SECONDS));
// Racy external submission: CASing state from ST_SUSPENDED to ST_STARTED.
// Despite the race, this *should* punt the executor thread back to started *or* start a new executor
// thread (which will wait for the existing one to completely finish its suspension).
LatchTask raced = new LatchTask();
executor.execute(raced);
// Let the old executor thread finish suspending.
externalDone.countDown();
// The expected behavior is that the raced task must eventually run, and not leave the executor stuck
// in ST_STARTED state with no actual thread started.
assertTrue(raced.await(10, TimeUnit.SECONDS));
executor.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly();
}| } | ||
| } | ||
|
|
||
| private final Runnable neverStartedQuietPeriodTask = new Runnable() { |
There was a problem hiding this comment.
Move this declaration up with the other fields.
When shutdownGracefully() runs on an executor that was never started and has no pending work, terminate without creating a worker thread. MultithreadEventExecutorGroup walks every child on shutdown; without this path, constructing a group of N and shutting it down unused spun up all N threads only to exit immediately (netty#17135).
Local SingleThreadEventExecutorTest is 18/18 green (JDK 21).
CI failures (TestLens / KQueue / Nio) showed AssertionError in SingleThreadIoEventLoop.cleanup() when tryTerminateIfNeverStarted called cleanup() off the event-loop thread. - Bind current thread for cleanup so constructor-created IoHandler is destroyed - Only fast-path when quietPeriod == 0 (honor graceful quiet period otherwise) - MultithreadEventExecutorGroup uses quietPeriod=0 for never-started children so default shutdownGracefully() no longer starts unused workers (netty#17135)
Never-started MultithreadEventExecutorGroup children still force quietPeriod=0 so unused workers are not started. Document that late execute after group.shutdownGracefully(nonZero) is rejected on those children, and add a regression test covering that contract.
Never-started executors with a non-zero quiet period stay SHUTTING_DOWN without starting a worker, schedule a GlobalEventExecutor timer to terminate when quiet elapses with no work, and start a worker only if execute() arrives during the quiet period. MultithreadEventExecutorGroup no longer forces quietPeriod=0 on unused children. Addresses mega12345mega's design feedback on netty#17183 / netty#17135. Signed-off-by: arimu1 <[email protected]>
SingleThreadEventExecutor.tryTerminateIfNeverStarted() calls cleanup() off-thread before run()/initialize(). IoUring rings are created disabled; destroy()'s submission path needs enable() first, which caused io_uring_enter error -77 in IoUringEventLoopTest.shutdownBeforeStart. Skip submission-based teardown when initialize() never ran; release buffer rings and close the ring directly instead. Fixes CI failures reported on netty#17183. Signed-off-by: arimu1 <[email protected]>
…d isNeverStarted Norman noted the group-level comment-only change was unnecessary. Zero-diff that file vs 4.2 and delete the unused never-started helper. Signed-off-by: arimu1 <[email protected]>
When execute() CASes ST_SUSPENDED to ST_STARTED while the event-loop thread is still winding down, re-engage that thread or wake it so tasks are not left on a started executor with no worker. Includes regression test from review and moves neverStartedQuietPeriodTask with other fields.
4936f8c to
3373ed5
Compare
|
@chrisvest Thanks for catching the suspension race. What went wrong: While the event-loop thread is winding down through Fix:
Included your regression test ( Local (Temurin 21): |
…work arrived After canSuspend(ST_SUSPENDED) returns true, execute() may still CAS to ST_STARTED while threadStartIssued is held during removeAll(). Recheck state after clearing the start gate and issue a replacement worker when needed. Adds regression test for that window and restores chrisvest's test comments for the re-engage interleaving.
|
Follow-up on @chrisvest's suspend/execute race review — the re-engage path inside the second
Fix: after Tests:
Prove-it (Temurin 21): with the finally-recheck stashed, the new test times out at 10s; with it restored, Tip: |
|
@franz1981 PTAL as well |
|
@arimu1 I have some concern on this - but knowing what problem is trying to solve, will help me understand if the added complexity is worthy. micronaut-projects/micronaut-core#12887 seems the only "prod-grade" issue which looks to dependent on this, but as @normanmaurer answered on that issue, "why it was working before"? |
Motivation: Since #15766, `trySuspend()` moves an executor that was never started directly from `ST_NOT_STARTED` to `ST_SUSPENDED`. `startThread()` reads the state once and then does a single CAS from that value to `ST_STARTED`: ```java int currentState = state; if (currentState == ST_NOT_STARTED || currentState == ST_SUSPENDED) { if (STATE_UPDATER.compareAndSet(this, currentState, ST_STARTED)) { ``` If `trySuspend()` runs between the read and the CAS, the CAS fails and `startThread()` returns without starting a thread. The task that `execute()` just added then sits in the queue of an executor that reports `isSuspended() == true` and has no thread. It only runs if something else is submitted later. `AutoScalingEventExecutorChooserFactory` can hit this: its monitor calls `trySuspend()` on idle executors that were never started, while `next()` may still hand the same executor out. A `Channel` registration on such an event loop never completes, and because the loop is no longer in the active set, nothing else is likely to wake it. Modification: Re-read the state and retry the CAS in `startThread()` while the state is still `ST_NOT_STARTED` or `ST_SUSPENDED` (the `if` becomes a `while`, plus a `break` after a successful start). The loop only retries when another thread changed the state between the read and the CAS, so it cannot spin: each extra round needs a new state change by someone else. It can take more than two rounds, though. For example, the CAS loses to `trySuspend()` (`ST_NOT_STARTED` to `ST_SUSPENDED`), then another thread's `startThread()` wins, its `doStartThread()` fails and it resets the state to `ST_NOT_STARTED`, and then this thread retries again. Any state other than `ST_NOT_STARTED` or `ST_SUSPENDED` means another thread started the executor, the old thread re-engaged, or the executor is shutting down, and each of those already takes care of the queued task. The retry may deliberately un-suspend an executor that `trySuspend()` has just suspended. That is the same thing `execute()` already does for an executor that is suspended, and the code comment at the retry says so. Add `SingleThreadEventExecutorTest.testExecuteRacingTrySuspendWhenExecutorIsNotStarted`. The race cannot be forced deterministically because there is no hook between the state read and the CAS, so the test repeats `execute()` against a concurrent `trySuspend()` on fresh executors 10000 times. The executors use an `Executor` that only counts start requests, so no threads are created and the check (exactly one start request per `execute()`) is exact. It takes about 0.1s. The test is regression-sensitive, not deterministic. Without the fix it needs the two threads to actually run in parallel and hit the window between the read and the CAS, so it may pass on machines with only 1 or 2 CPUs. With the fix it cannot fail falsely: every interleaving leads to exactly one start request. Result: A task added by `execute()` always gets a thread, even if it races with `trySuspend()`. This regressed in #15766. Testing: - Without the fix the new test failed in every run on a 12-CPU machine, typically within the first 20 to 140 iterations, for example: `AssertionFailedError: iteration 69 (isSuspended=true) ==> expected: <1> but was: <0>` As said above, it may pass without the fix on machines with 1 or 2 CPUs. - With the fix: `SingleThreadEventExecutorTest` 16 tests, 0 failures; `common` module 1449 tests, 0 failures, 19 skipped; checkstyle passes. - Standalone harnesses against the real classes: `execute()` racing `trySuspend()` stranded the task in 5445 of 300000 iterations before the fix and 0 of 300000 after. `SingleThreadIoEventLoop.register(channel)` on NIO racing `trySuspend()` hung 39 of 4000 registrations before and 0 of 3000 after. Interaction with open PRs: - #17601 (port of #17589) changes the post-`run()` decision in `doStartThread()`, a different code path (a running thread that is suspending). The two merge cleanly, and `SingleThreadEventExecutorTest` passes with both (17 tests). The model below was checked with both fixes applied. - #17183 and #15813 also edit `startThread()` and conflict textually, since this change turns the `if` into a `while`. Their extra `else if` branch moves after the loop as a plain `if` on the last observed state. With that resolution the tests pass for this change with #17183 (23 tests) and with #15813 (`SingleThreadEventExecutorTest` and `AutoScalingEventExecutorChooserFactoryTest`, 24 tests). This was found with a TLA+ model of the executor state machine (liveness property "an accepted task eventually runs" violated) and reproduced with the real classes. With the retry, the model passes `MutualExclusion`, `RunningHasThread` and `TaskRuns`/`TaskResolved`. It was checked alone and together with the #17589 fix (where it also passes `NoSpuriousShutdown`), with 2 submitters, up to 2 `trySuspend()` calls, graceful shutdown and scheduled-task cancellation, starting from both `ST_NOT_STARTED` and `ST_STARTED`, up to 1.44M distinct states. Co-authored-by: Norman Maurer <[email protected]>
…hread() (#17654) Auto-port of #17608 to 5.0 Cherry-picked commit: c4e7d1e --- Motivation: Since #15766, `trySuspend()` moves an executor that was never started directly from `ST_NOT_STARTED` to `ST_SUSPENDED`. `startThread()` reads the state once and then does a single CAS from that value to `ST_STARTED`: ```java int currentState = state; if (currentState == ST_NOT_STARTED || currentState == ST_SUSPENDED) { if (STATE_UPDATER.compareAndSet(this, currentState, ST_STARTED)) { ``` If `trySuspend()` runs between the read and the CAS, the CAS fails and `startThread()` returns without starting a thread. The task that `execute()` just added then sits in the queue of an executor that reports `isSuspended() == true` and has no thread. It only runs if something else is submitted later. `AutoScalingEventExecutorChooserFactory` can hit this: its monitor calls `trySuspend()` on idle executors that were never started, while `next()` may still hand the same executor out. A `Channel` registration on such an event loop never completes, and because the loop is no longer in the active set, nothing else is likely to wake it. Modification: Re-read the state and retry the CAS in `startThread()` while the state is still `ST_NOT_STARTED` or `ST_SUSPENDED` (the `if` becomes a `while`, plus a `break` after a successful start). The loop only retries when another thread changed the state between the read and the CAS, so it cannot spin: each extra round needs a new state change by someone else. It can take more than two rounds, though. For example, the CAS loses to `trySuspend()` (`ST_NOT_STARTED` to `ST_SUSPENDED`), then another thread's `startThread()` wins, its `doStartThread()` fails and it resets the state to `ST_NOT_STARTED`, and then this thread retries again. Any state other than `ST_NOT_STARTED` or `ST_SUSPENDED` means another thread started the executor, the old thread re-engaged, or the executor is shutting down, and each of those already takes care of the queued task. The retry may deliberately un-suspend an executor that `trySuspend()` has just suspended. That is the same thing `execute()` already does for an executor that is suspended, and the code comment at the retry says so. Add `SingleThreadEventExecutorTest.testExecuteRacingTrySuspendWhenExecutorIsNotStarted`. The race cannot be forced deterministically because there is no hook between the state read and the CAS, so the test repeats `execute()` against a concurrent `trySuspend()` on fresh executors 10000 times. The executors use an `Executor` that only counts start requests, so no threads are created and the check (exactly one start request per `execute()`) is exact. It takes about 0.1s. The test is regression-sensitive, not deterministic. Without the fix it needs the two threads to actually run in parallel and hit the window between the read and the CAS, so it may pass on machines with only 1 or 2 CPUs. With the fix it cannot fail falsely: every interleaving leads to exactly one start request. Result: A task added by `execute()` always gets a thread, even if it races with `trySuspend()`. This regressed in #15766. Testing: - Without the fix the new test failed in every run on a 12-CPU machine, typically within the first 20 to 140 iterations, for example: `AssertionFailedError: iteration 69 (isSuspended=true) ==> expected: <1> but was: <0>` As said above, it may pass without the fix on machines with 1 or 2 CPUs. - With the fix: `SingleThreadEventExecutorTest` 16 tests, 0 failures; `common` module 1449 tests, 0 failures, 19 skipped; checkstyle passes. - Standalone harnesses against the real classes: `execute()` racing `trySuspend()` stranded the task in 5445 of 300000 iterations before the fix and 0 of 300000 after. `SingleThreadIoEventLoop.register(channel)` on NIO racing `trySuspend()` hung 39 of 4000 registrations before and 0 of 3000 after. Interaction with open PRs: - #17601 (port of #17589) changes the post-`run()` decision in `doStartThread()`, a different code path (a running thread that is suspending). The two merge cleanly, and `SingleThreadEventExecutorTest` passes with both (17 tests). The model below was checked with both fixes applied. - #17183 and #15813 also edit `startThread()` and conflict textually, since this change turns the `if` into a `while`. Their extra `else if` branch moves after the loop as a plain `if` on the last observed state. With that resolution the tests pass for this change with #17183 (23 tests) and with #15813 (`SingleThreadEventExecutorTest` and `AutoScalingEventExecutorChooserFactoryTest`, 24 tests). This was found with a TLA+ model of the executor state machine (liveness property "an accepted task eventually runs" violated) and reproduced with the real classes. With the retry, the model passes `MutualExclusion`, `RunningHasThread` and `TaskRuns`/`TaskResolved`. It was checked alone and together with the #17589 fix (where it also passes `NoSpuriousShutdown`), with 2 submitters, up to 2 `trySuspend()` calls, graceful shutdown and scheduled-task cancellation, starting from both `ST_NOT_STARTED` and `ST_STARTED`, up to 1.44M distinct states. Co-authored-by: allthingssecurity <[email protected]> Co-authored-by: Norman Maurer <[email protected]>
allthingssecurity
left a comment
There was a problem hiding this comment.
I ran the executor tests and a race harness against this PR: head 5c5bf0f585, and the same head merged locally with
current 4.2.
A task accepted by execute() is dropped, and a worker starts after termination.
tryTerminateIfNeverStarted() checks the queue one last time (SingleThreadEventExecutor.java:1321-1324) and then
moves ST_SHUTTING_DOWN to ST_TERMINATED (:1325). A concurrent execute() can run entirely between those two
steps:
addTask(task).startThread()seesST_SHUTTING_DOWN && thread == null(:1186) and callsissueDoStartThread(). The new worker
blocks onprocessingLock(:1360), which the terminating thread holds.isShutdown()is still false, because the state isST_SHUTTING_DOWNand not yetST_SHUTDOWN. Soexecute()
neither removes nor rejects the task and returns normally.
The terminating thread then does the CAS, runs cleanup(), and drainTasks() (:1341) throws the task away with
"An event executor terminated with non-empty task queue (1)". The caller's task is neither run nor rejected.
Once the lock is released, the worker takes it and enters run() on the terminated executor, after cleanup():
- With a
DefaultEventExecutor-stylerun(), it parks intakeTask()forever, because the wakeup task was drained as
well. The thread leaks. My stress JVM with non-daemon threads did not exit aftermainreturned, and the thread dump
showed the worker intakeTask(). - If that worker is interrupted, it goes through termination a second time:
cleanup()runs again and
terminationFuture.setSuccessthrowsIllegalStateException: complete already. - For a
SingleThreadIoEventLoop(from reading the code), the late worker would callioHandler.initialize()after
destroy(), thendestroy()a second time fromcleanup().
The comment at :1297 says taking processingLock avoids racing with a just-started worker. That only covers a
worker started before the tryLock(). A worker issued while this method runs just waits for the lock.
Deterministic reproducer (run on this PR merged with 4.2, so the line number in the trace comes from that merge). A
newTaskQueue() override pauses the shutting-down thread inside the second
isEmpty() call made from tryTerminateIfNeverStarted(), and another thread calls execute() meanwhile:
hook fired (window between last empty check and CAS to TERMINATED): true
execute() returned normally: true, task ran: false, rejected: false
terminationFuture done: true, isTerminated: true, cleanup() calls: 1
worker thread started: true, run() entered after cleanup(): true, still alive 500ms after termination: true (WAITING)
Exception in thread "det-1-1" java.lang.IllegalStateException: complete already: DefaultPromise@...(success)
at io.netty.util.concurrent.SingleThreadEventExecutor$6.run(SingleThreadEventExecutor.java:1486)
after interrupting the worker: alive=false, cleanup() calls: 2
On 4.2 this window does not exist: the executor is shut down by its own worker, and the late execute() is rejected.
Without hooks. Each iteration runs shutdownGracefully(0, 0, SECONDS) against execute() on a fresh, never-started
executor, with the two threads released by a barrier plus a random spin, and 4 busy-loop CPU hogs running:
| Build | Iterations | Tasks lost (not run, not rejected) | Workers in run() after cleanup() |
|---|---|---|---|
| PR head | 43,000 (3k + 10k + 30k) | 6 | 1 (that one never exited) |
| PR merged with 4.2 | 30,000 | 3 | 0 |
| 4.2 | 73,000 | 0 | 0 |
Possible direction. The never-started termination and the ST_SHUTTING_DOWN start in startThread() need to
exclude each other. One way:
- claim
threadStartIssuedintryTerminateIfNeverStarted()before the final emptiness check, so no worker can be
issued after that check; - move to
ST_SHUTDOWNbefore the check, as the worker path does at:1430-1441. A concurrentexecute()then either
has its task seen by the check (start a worker, as now), or its ownisShutdown()check rejects the task.
Merge conflict with #17608. #17608 (merged yesterday) turned the if in startThread() into a while that
re-reads the state after a lost CAS, and this PR now conflicts with 4.2 there. I resolved it locally like this:
- keep the loop;
- move the
ST_SHUTTING_DOWN && thread == nullbranch into a separateifafter it. After a successful start the loop
breaks withcurrentStatestillNOT_STARTEDorSUSPENDED, so that branch is skipped.
With that resolution these all pass:
SingleThreadEventExecutorTest, 24 tests, including this PR's tests and #17608's
testExecuteRacingTrySuspendWhenExecutorIsNotStarted;GlobalEventExecutorTest, 6 tests.
The race above is unchanged after the merge (3 lost in 30,000).
Claude Code on behalf of allthingssecurity
| if (!taskQueue.isEmpty() || nextScheduledTaskDeadlineNanos() != -1 || !shutdownHooks.isEmpty()) { | ||
| return false; | ||
| } | ||
| if (STATE_UPDATER.compareAndSet(this, currentState, ST_TERMINATED)) { |
There was a problem hiding this comment.
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
| } | ||
| } | ||
| } | ||
| } else if (currentState == ST_SHUTTING_DOWN && thread == null) { |
There was a problem hiding this comment.
This branch can issue a worker after tryTerminateIfNeverStarted() did its last queue check. That worker then runs
after cleanup(): it parks in takeTask() forever, or runs cleanup() a second time if interrupted. It needs to be
mutually exclusive with the inline termination, for example through threadStartIssued.
Claude Code on behalf of allthingssecurity
| * a thread; {@code false} if a thread still needs to be started to drain work / run shutdown. | ||
| */ | ||
| private boolean tryTerminateIfNeverStarted() { | ||
| // Try to take the processing lock so we do not race with a just-started worker thread. |
There was a problem hiding this comment.
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
Keep the netty#17608 startThread retry loop, and run the never-started SHUTTING_DOWN worker start only after that loop.
…nation tryTerminateIfNeverStarted() checked the queue and then jumped to TERMINATED while the executor was still SHUTTING_DOWN, so a concurrent execute() could enqueue a task and start a worker that ran after cleanup(). Publish SHUTDOWN before the last emptiness check and hold the start gate so the task is rejected or a worker drains it. Signed-off-by: arimu1 <[email protected]>
|
Addressed the race in fae4cca, and merged current
|
🚨 TestLens detected 2 failed tests 🚨Test SummaryTip Inspect all details with the TestLens CLI: Build PR / linux-x86_64-java11-boringssl build > Netty/Handler/Ssl/Ocsp
Build PR / macos-aarch64-java11-boringssl build > Netty/Transport/Native/KQueue
🏷️ Commit: 378d158 Test FailuresOcspServerCertificateValidatorTest > connectUsingHttpAndValidateCertificateUsingOcspTest() (Netty/Handler/Ssl/Ocsp in Build PR / linux-x86_64-java11-boringssl build)
KQueueDatagramUnicastIPv6MappedTest > testSimpleSendDirectByteBuf(TestInfo) (Netty/Transport/Native/KQueue in Build PR / macos-aarch64-java11-boringssl build)Rerun ControlsSelect tests to mute in this pull request:
Reuse successful test results:
Click the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
|
These changes are looking increasingly complicated and fragile, so I'm starting to think that either the approach is wrong, or the juice might not be worth the squeeze. |
|
I agree with @chrisvest here |
|
Closing this |
Motivation:
MultithreadEventExecutorGroup.shutdownGracefully()(and thereforeMultiThreadIoEventLoopGroup) callsshutdownGracefullyon every childexecutor. Each child is a lazily started
SingleThreadEventExecutor.shutdown0()always calledensureThreadStarted()forST_NOT_STARTED, which spun up a worker thread solely so it could exiton the normal shutdown path. Constructing a large unused group and
shutting it down therefore started every thread:
See #17135.
Modification:
In
SingleThreadEventExecutor.ensureThreadStarted(), when the priorstate was
ST_NOT_STARTEDand there is no pending work (empty taskqueue, no scheduled tasks, no shutdown hooks), transition directly to
ST_TERMINATEDunder the processing lock and completeterminationFuturewithout creating a thread.If work is present (or the processing lock is already held by a worker),
fall back to the existing
doStartThread()path so tasks still run andshutdown hooks still execute.
Result:
Fixes #17135.
SingleThreadEventExecutorTestTested:
./mvnw -pl common test -Dtest=SingleThreadEventExecutorTest(18/18 green, JDK 21)