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 — Changes for Auto Scaling Netty threads by isaacrivriv · Pull Request #15797 · netty/netty

Conversation

@isaacrivriv

@isaacrivriv isaacrivriv commented Oct 27, 2025

Copy link
Copy Markdown
Contributor

Changes

  • Added changes for pausing executors that are idle to finish up active connections before being suspended
  • Updated pom.xml for issues compiling changes due to revapi

Motivation:

Idle executors still handling connections are not properly suspended and would remain active even if under the down scale threshold for as long as at least one connection remains active.

Modification:

Added a set of paused executors to the AutoScaling state and appropriate logic to manage idle executors which are still handling connections. Also updated pom.xml for issues compiling changes due to revapi

Result:

Fixes #15777

Sorry, something went wrong.

Uh oh!

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

franz1981 reacted with heart emoji
All reactions
  • ❤️ 1 reaction
@isaacrivriv isaacrivriv mentioned this pull request Oct 27, 2025
AutoScalingEventExecutorChooserFactory not properly scaling threads #15777
Open
normanmaurer
normanmaurer requested changes Oct 27, 2025
View reviewed changes
Comment thread common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java Resolved

Uh oh!

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

Comment thread common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java Resolved

Uh oh!

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

@franz1981

franz1981 commented Oct 27, 2025 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor

Will wait once ready, and will take a look :)

All reactions

Sorry, something went wrong.

Uh oh!

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

@franz1981

franz1981 commented Oct 27, 2025

Copy link
Copy Markdown
Contributor

At a first look (I have still to debug it) the paused executor set shouldn't be passed from the old to the new state as it is but need to be re-created new, without modifying the old one which could be a accessed concurrently by others which try to update the state

All reactions

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv

isaacrivriv commented Oct 28, 2025

Copy link
Copy Markdown
Contributor Author

Yeah as I was working on this I was thinking about that too and wondering what could happen. From my understanding, the only other code that could clash with the UtilizationMonitor which decides the scale up/down process would be the next method call from the AutoScalingEventExecutorChooser and only if the number of active executors is 0 where a scale up is attempted.

        @Override
        public EventExecutor next() {
            // Get a snapshot of the current state.
            AutoScalingState currentState = this.state.get();


            if (currentState.activeExecutors.length == 0) {
                // This is only reachable if minChildren is 0 and the monitor has just suspended the last active thread.
                // To prevent an error and ensure the group can recover, we wake one up and use the
                // chooser that contains all executors as a safe temporary choice.
                tryScaleUpBy(1);
                return allExecutorsChooser.next();
            }
            return currentState.activeExecutorsChooser.next();
        }

Before the changes given that the state could be modified from another thread, I thought race conditions could occur but I noticed the "infinite" for loop in the tryScaleUpBy method attempting to modify the state with compareAndSet and thought that should cover if another thread attempted to change the state and also cover the paused executor as well? I can test locally with 0 threads to see if I notice any weirdness. Either way, it does make it cleaner to have a unique set for each state but I was trying to limit if possible the number of new objects we create on each state change though in practice I don't know how worth it this is since maybe the number of threads shouldn't be that many/the state changes shouldn't be too many?

franz1981 reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv

isaacrivriv commented Oct 28, 2025

Copy link
Copy Markdown
Contributor Author

I just added a test to verify that idle executors with registered channels should not be suspended while also not be reported as active executors. This should now be ready for review

franz1981 reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv
isaacrivriv marked this pull request as ready for review October 28, 2025 14:55
@franz1981

franz1981 commented Oct 28, 2025

Copy link
Copy Markdown
Contributor

I don't know how worth it this is since maybe the number of threads shouldn't be that many/the state changes shouldn't be too many?

in theory for each (successfull) state change. you can still reuse the newly allocated Set till the state change happen/abandoned.

Re been the "right thing to do" IDK yet;

netty/common/src/main/java/io/netty/util/concurrent/GlobalEventExecutor.java

Line 39 in 4a88cd6

* Single-thread singleton {@link EventExecutor}. It starts the thread automatically and stops it when there is no
is single threaded, for example (IIRC)

isaacrivriv reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv

isaacrivriv commented Oct 28, 2025

Copy link
Copy Markdown
Contributor Author

While testing with minChildren = 0 I ran into some weird behavior when attempting to scale down after scaling up from 0 where no attempt to scale down was done even without the changes to pause the active executors. I opened #15809 to discuss

All reactions

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv

isaacrivriv commented Nov 4, 2025

Copy link
Copy Markdown
Contributor Author

Ping to see if we can get this reviewed/merged in... not sure if we would like #15813 as a prereq before merging these changes

All reactions

Sorry, something went wrong.

Uh oh!

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

@normanmaurer

normanmaurer commented Nov 7, 2025

Copy link
Copy Markdown
Member

ping @georgebanasios

All reactions

Sorry, something went wrong.

Uh oh!

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

@georgebanasios

georgebanasios commented Nov 8, 2025

Copy link
Copy Markdown
Contributor

lgtm

All reactions

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv isaacrivriv mentioned this pull request Sep 18, 2026
Reset busy counters after triggering an auto-scale-up decision #17538
Merged
@isaacrivriv isaacrivriv mentioned this pull request Oct 22, 2026
Update state in SingleThreadEventExecutor from SUSPENDING to STARTED on new work #15813
Open
@isaacrivriv
isaacrivriv force-pushed the 15777-autoScaler-pause-executors branch from 2d0fc40 to d8982d3 Compare October 22, 2026 19:14
isaacrivriv and others added 4 commits October 22, 2026 15:19
@isaacrivriv
Changes for Auto Scaling Netty threads
64e8578
- Added changes for pausing executors that are idle to finish up active
  connections before being suspended
@isaacrivriv @normanmaurer
Clean up unnecessary contains check for paused executors
ee43792
Co-authored-by: Norman Maurer <[email protected]>
@isaacrivriv @normanmaurer
Clean up unnecessary contains check for paused executors on scale up
a349240
Co-authored-by: Norman Maurer <[email protected]>
@isaacrivriv
Added test for verifying executors with registered channels are not s…
581e494
…uspended
@isaacrivriv
isaacrivriv force-pushed the 15777-autoScaler-pause-executors branch from d8982d3 to 581e494 Compare October 22, 2026 19:19
@isaacrivriv

isaacrivriv commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

@normanmaurer @franz1981 should be ready for review/merge when you get a chance

All reactions

Sorry, something went wrong.

Uh oh!

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

@normanmaurer

normanmaurer commented Oct 23, 2026

Copy link
Copy Markdown
Member

I found two concurrency problems in how pausedExecutors is handled and have a possible fix, including a test that fails on the current code. Details below.

What goes wrong in the current code

AutoScalingState is documented as an immutable snapshot that is only changed by atomically swapping it, but pausedExecutors is a single mutable Set that is shared by reference across every snapshot. Changes to it are therefore not covered by the CAS.

1. tryScaleUpBy removes from the shared set before the CAS

} else if (oldState.pausedExecutors.remove(stee)) {   // mutates the shared set
    wokenUp.add(stee);
}
...
if (state.compareAndSet(oldState, newState)) { return; }
// CAS failed -> loop again

If the CAS fails, the removal has already happened. On the retry the executor is neither suspended nor paused, so it is skipped. It is not in any activeExecutors array and is not counted in activeChildrenCount, so it keeps running but never gets new connections. The "state differs from our view" check in the monitor (currentActive != activeExecutors.length) never fires, because the count and the array are always set together. The executor only comes back with the next scale-down rebuild.

This needs two threads. The monitor can't race itself (scheduleAtFixedRate), but next() calls tryScaleUpBy(1) whenever the active list is empty (minThreads=0). Several threads in next() can then each un-pause a different paused executor, one CAS wins, and the others lose the executor they removed. A monitor rebuildActiveExecutors scan that completes between the removal and the CAS has the same effect.

2. next() with an empty active list un-pauses an arbitrary executor

tryScaleUpBy(1);
EventExecutor executor = allExecutorsChooser.next();     // not necessarily the executor that was woken
this.state.get().pausedExecutors.remove(executor);       // outside any CAS

allExecutorsChooser round-robins over all executors, so the executor it returns is not necessarily the one tryScaleUpBy just woke. It is also taken out of the paused set without being added to the active array or counted. It then serves traffic while the state doesn't know about it.

Fix

  • pausedExecutors is now final and never modified after construction. Every transition builds a new set and publishes it with the CAS.
  • tryScaleUpBy works on a copy of the paused set, publishes it only if the CAS succeeds, and returns the executor it actually added. It also resets the idle/busy cycles of the executors it woke, so they aren't immediately paused again.
  • next() uses the executor returned by tryScaleUpBy. If nothing was woken, it re-reads the state and falls back to allExecutorsChooser without touching the paused set.
  • The monitor no longer mutates the paused set during its run. It collects toPause / toUnpause locally and rebuildActiveExecutors applies them on top of the latest state on each CAS attempt, so concurrent scale-ups aren't overwritten.

Test

testConcurrentNextWithAllExecutorsPausedKeepsStateConsistent pauses all executors with minThreads=0, then has 16 threads call group.next() at the same time. Every executor that is returned must be an active executor, and activeExecutorCount() must match the number of active executors. It failed 3/3 runs on the current PR code and passed on repeated runs with the fix. The whole AutoScalingEventExecutorChooserFactoryTest class passes (9 tests). It takes about 6s because it has to wait for the pause cycles.

Diff against the PR head (581e494ad1)
diff --git a/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java b/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java
index ff9efbdabf..6f0bdf67d3 100644
--- a/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java
+++ b/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java
@@ -19,9 +19,9 @@ import io.netty.util.internal.ObjectUtil;
 
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.atomic.AtomicReference;
@@ -145,10 +145,11 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
         final long nextWakeUpIndex;
         final EventExecutor[] activeExecutors;
         final EventExecutorChooser activeExecutorsChooser;
-        Set<SingleThreadEventExecutor> pausedExecutors;
+        // Never mutated after construction, a new set is created for every state transition.
+        final Set<SingleThreadEventExecutor> pausedExecutors;
 
         AutoScalingState(int activeChildrenCount, long nextWakeUpIndex, EventExecutor[] activeExecutors) {
-            this(activeChildrenCount, nextWakeUpIndex, activeExecutors, ConcurrentHashMap.newKeySet());
+            this(activeChildrenCount, nextWakeUpIndex, activeExecutors, Collections.emptySet());
         }
 
         AutoScalingState(int activeChildrenCount, long nextWakeUpIndex, EventExecutor[] activeExecutors,
@@ -200,15 +201,18 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                 // This is only reachable if minChildren is 0 and the monitor has just suspended the last active thread.
                 // To prevent an error and ensure the group can recover, we wake one up and use the
                 // chooser that contains all executors as a safe temporary choice.
-                tryScaleUpBy(1);
-                EventExecutor executor = allExecutorsChooser.next();
-                this.state.get().pausedExecutors.remove(executor);
-                if (executor instanceof SingleThreadEventExecutor) {
-                    SingleThreadEventExecutor stee = (SingleThreadEventExecutor) executor;
-                    stee.resetIdleCycles();
-                    stee.resetBusyCycles();
+                EventExecutor woken = tryScaleUpBy(1);
+                if (woken != null) {
+                    return woken;
                 }
-                return executor;
+                // Another thread may have woken an executor in the meantime, so look at the latest state.
+                currentState = this.state.get();
+                if (currentState.activeExecutors.length > 0) {
+                    return currentState.activeExecutorsChooser.next();
+                }
+                // Nothing could be woken up. Fall back to any executor without touching the state, submitting
+                // a task will resume it if it is suspended.
+                return allExecutorsChooser.next();
             }
             return currentState.activeExecutorsChooser.next();
         }
@@ -218,20 +222,24 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
          * This method is thread-safe and updates the state atomically.
          *
          * @param amount    The desired number of threads to add to the active count.
+         * @return          the first executor that was added to the active executors, or {@code null} if none was.
          */
-        private void tryScaleUpBy(int amount) {
+        private EventExecutor tryScaleUpBy(int amount) {
             if (amount <= 0) {
-                return;
+                return null;
             }
 
             for (;;) {
                 AutoScalingState oldState = state.get();
                 if (oldState.activeChildrenCount >= maxChildren) {
-                    return;
+                    return null;
                 }
 
                 int canAdd = Math.min(amount, maxChildren - oldState.activeChildrenCount);
                 List<EventExecutor> wokenUp = new ArrayList<>(canAdd);
+                // The paused set of a published state must never be modified, so work on a copy that is only
+                // published if the CAS succeeds.
+                Set<SingleThreadEventExecutor> newPaused = new HashSet<>(oldState.pausedExecutors);
                 final long startIndex = oldState.nextWakeUpIndex;
 
                 for (int i = 0; i < executors.length; i++) {
@@ -244,16 +252,17 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                         SingleThreadEventExecutor stee = (SingleThreadEventExecutor) child;
                         if (stee.isSuspended()) {
                             stee.execute(NO_OOP_TASK);
+                            newPaused.remove(stee);
                             wokenUp.add(stee);
-                        } else if (oldState.pausedExecutors.remove(stee)) {
-                            // Remove from the paused list so that it can accept connections once again
+                        } else if (newPaused.remove(stee)) {
+                            // Removed from the paused set so that it can accept connections once again.
                             wokenUp.add(stee);
                         }
                     }
                 }
 
                 if (wokenUp.isEmpty()) {
-                    return;
+                    return null;
                 }
 
                 // Create the new state.
@@ -265,10 +274,16 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                         oldState.activeChildrenCount + wokenUp.size(),
                         startIndex + wokenUp.size(),
                         newActiveList.toArray(new EventExecutor[0]),
-                        oldState.pausedExecutors);
+                        newPaused);
 
                 if (state.compareAndSet(oldState, newState)) {
-                    return;
+                    for (EventExecutor executor : wokenUp) {
+                        // Give the executor a full patience period before it can be paused or suspended again.
+                        SingleThreadEventExecutor stee = (SingleThreadEventExecutor) executor;
+                        stee.resetIdleCycles();
+                        stee.resetBusyCycles();
+                    }
+                    return wokenUp.get(0);
                 }
                 // CAS failed, another thread changed the state. Loop again to retry.
             }
@@ -288,6 +303,9 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
             private final List<SingleThreadEventExecutor> consistentlyIdleChildren = new ArrayList<>(maxChildren);
             private final List<SingleThreadEventExecutor> consistentlyBusyChildren = new ArrayList<>(maxChildren);
             private final List<SingleThreadEventExecutor> drainingIdleChildren = new ArrayList<>(maxChildren);
+            // Changes to the paused set decided in a single run, applied to the latest state when rebuilding.
+            private final Set<SingleThreadEventExecutor> toPause = new HashSet<>();
+            private final Set<SingleThreadEventExecutor> toUnpause = new HashSet<>();
             private long lastCheckTimeNanos;
 
             @Override
@@ -321,12 +339,14 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                 consistentlyIdleChildren.clear();
                 consistentlyBusyChildren.clear();
                 drainingIdleChildren.clear();
+                toPause.clear();
+                toUnpause.clear();
 
                 final AutoScalingState currentState = state.get();
                 // Attempt to suspend current paused children if possible.
                 for (SingleThreadEventExecutor pausedChild : currentState.pausedExecutors) {
                     if (pausedChild.getNumOfRegisteredChannels() <= 0 && pausedChild.trySuspend()) {
-                        currentState.pausedExecutors.remove(pausedChild);
+                        toUnpause.add(pausedChild);
                     }
                 }
 
@@ -424,7 +444,7 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                                 idleChild.resetIdleCycles();
                             } else {
                                 // If failed to suspend, we add it to the paused children to later be able to suspend it
-                                currentState.pausedExecutors.add(idleChild);
+                                toPause.add(idleChild);
                             }
                             changed = true;
                         }
@@ -440,7 +460,7 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                             int threadsPaused = 0;
                             // Iterate children to drain and add it to the list of paused children
                             while (threadsPaused < threadsToPause) {
-                                currentState.pausedExecutors.add(drainingIdleChildren.get(threadsPaused++));
+                                toPause.add(drainingIdleChildren.get(threadsPaused++));
                             }
                             changed = true;
                         }
@@ -448,20 +468,25 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                 }
 
                 // If a scale-down occurred, or if the actual state differs from our view, rebuild.
-                if (changed || currentActive != currentState.activeExecutors.length) {
+                if (changed || !toUnpause.isEmpty() || currentActive != currentState.activeExecutors.length) {
                     rebuildActiveExecutors();
                 }
             }
 
             /**
              * Atomically updates the state by creating a new snapshot with the current set of active executors.
+             * The pending paused set changes are applied on top of the latest state on every attempt, so that
+             * concurrent changes done by {@link #tryScaleUpBy(int)} are not lost.
              */
             private void rebuildActiveExecutors() {
                 for (;;) {
                     AutoScalingState oldState = state.get();
+                    Set<SingleThreadEventExecutor> newPaused = new HashSet<>(oldState.pausedExecutors);
+                    newPaused.removeAll(toUnpause);
+                    newPaused.addAll(toPause);
                     List<EventExecutor> active = new ArrayList<>(oldState.activeChildrenCount);
                     for (EventExecutor executor : executors) {
-                        if (!executor.isSuspended() && !oldState.pausedExecutors.contains(executor)) {
+                        if (!executor.isSuspended() && !newPaused.contains(executor)) {
                             active.add(executor);
                         }
                     }
@@ -471,7 +496,7 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                     // another thread likely changed it. We use the count from our fresh scan.
                     // The nextWakeUpIndex is preserved from the old state as this rebuild is not a scale-up action.
                     AutoScalingState newState = new AutoScalingState(newActiveExecutors.length,
-                            oldState.nextWakeUpIndex, newActiveExecutors, oldState.pausedExecutors);
+                            oldState.nextWakeUpIndex, newActiveExecutors, newPaused);
 
                     if (state.compareAndSet(oldState, newState)) {
                         break;
diff --git a/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java b/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java
index 3258a84e7c..0aba34f7bc 100644
--- a/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java
+++ b/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java
@@ -19,10 +19,17 @@ import io.netty.util.concurrent.AutoScalingEventExecutorChooserFactory.AutoScali
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.Timeout;
 
+import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CyclicBarrier;
 import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -419,6 +426,60 @@ public class AutoScalingEventExecutorChooserFactoryTest {
         }
     }
 
+    @Test
+    @Timeout(60)
+    void testConcurrentNextWithAllExecutorsPausedKeepsStateConsistent() throws Exception {
+        final int maxThreads = 8;
+        final int threads = 16;
+        final int timeWindowMs = 1000;
+        TestEventExecutorGroup group = new TestEventExecutorGroup(0, maxThreads, timeWindowMs, TimeUnit.MILLISECONDS);
+        ExecutorService callers = Executors.newFixedThreadPool(threads);
+        try {
+            startAllExecutors(group);
+            // Registered channels prevent the idle executors from being suspended, so they end up paused instead.
+            for (EventExecutor executor : group) {
+                ((TestEventExecutor) executor).getAndIncrementRegisteredChannels();
+            }
+
+            for (int round = 0; round < 2; round++) {
+                // Wait until all executors are paused, which leaves the group without any active executor.
+                final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15);
+                while (group.activeExecutorCount() > 0 && System.nanoTime() < deadline) {
+                    Thread.sleep(10);
+                }
+                assertEquals(0, group.activeExecutorCount(), "All executors should have been paused");
+
+                // Many threads racing to recover the group while there is no active executor.
+                final Set<EventExecutor> returned = ConcurrentHashMap.newKeySet();
+                final CyclicBarrier barrier = new CyclicBarrier(threads);
+                List<Future<?>> futures = new ArrayList<>(threads);
+                for (int i = 0; i < threads; i++) {
+                    futures.add(callers.submit(() -> {
+                        barrier.await();
+                        returned.add(group.next());
+                        return null;
+                    }));
+                }
+                for (Future<?> future : futures) {
+                    future.get(10, TimeUnit.SECONDS);
+                }
+
+                // Every executor handed out must be part of the active executors, otherwise it was woken without
+                // being tracked and will not receive any further work.
+                Set<EventExecutor> active = new HashSet<>();
+                for (int i = 0; i < 4 * maxThreads; i++) {
+                    active.add(group.next());
+                }
+                assertTrue(active.containsAll(returned),
+                        "Returned executors " + returned + " are not all active: " + active);
+                assertEquals(active.size(), group.activeExecutorCount());
+            }
+        } finally {
+            callers.shutdownNow();
+            group.shutdownGracefully().syncUninterruptibly();
+        }
+    }
+
     private static void startAllExecutors(MultithreadEventExecutorGroup group) throws InterruptedException {
         CountDownLatch startLatch = new CountDownLatch(group.executorCount());
         for (EventExecutor executor : group) {
isaacrivriv reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv
Fix race conditions in AutoScalingState pausedExecutors handling
bb3587a
- Ensure AutoScalingState remains strictly immutable by never mutating pausedExecutors in place.
- Produce a new set published via CAS to prevent losing executors during concurrent scale-up or rebuilds.
@testlens-app

testlens-app Bot commented Oct 23, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: bb3587a
▶️ Tests: 49385 executed
⚪️ Checks: 26/26 completed


Learn more about TestLens at testlens.app/docs.

All reactions

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv
isaacrivriv requested a review from normanmaurer October 28, 2026 16:07
@isaacrivriv

isaacrivriv commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@normanmaurer @franz1981 gentle review reminder to see if we can get this merged in

All reactions

Sorry, something went wrong.

Uh oh!

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

@isaacrivriv

isaacrivriv commented Nov 11, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor Author

Any chance we can follow up again on this PR to get it merged? Sorry for the continued pings @normanmaurer @franz1981

Same for https://github.com/netty/netty/pull/15813

All reactions

Sorry, something went wrong.

Uh oh!

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

@franz1981

franz1981 commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

PTAL @normanmaurer ? to me it looks good

All reactions

Sorry, something went wrong.

Uh oh!

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

franz1981
franz1981 approved these changes Nov 11, 2026
View reviewed changes

@franz1981 franz1981 left a comment

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.

LGTM!

Sorry, something went wrong.

Uh oh!

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

isaacrivriv reacted with rocket emoji
All reactions
  • 🚀 1 reaction
@normanmaurer

normanmaurer commented Nov 11, 2026

Copy link
Copy Markdown
Member

@isaacrivriv I think there is still one issue... what do you think of this fix:

From: Norman Maurer <[email protected]>
Date: Wed, 11 Nov 2026 15:26:56 +0100
Subject: [PATCH] Don't pause idle executors that fail to suspend in
 AutoScalingEventExecutorChooser

Motivation:

When an executor without registered channels was consistently idle but
trySuspend() failed (e.g. because suspension is not supported by the
executor), it was added to the paused executors. Such an executor has no
channels to drain and can never be suspended, so it was taken out of
rotation for good and only came back with a later scale-up. Before the
pausing of executors with active connections was introduced, nothing
changed in this case and the suspension was retried in the next cycle.

Modification:

Only pause executors that still have registered channels. If an idle
executor without channels can't be suspended it stays active and the
suspension is retried in the next cycle. The active executors are only
rebuilt when an executor was actually suspended.

Add a regression test that uses executors which don't support suspension.

Result:

Executors that can't be suspended are no longer removed from the active
executors by the auto-scaler.
---
 ...utoScalingEventExecutorChooserFactory.java |  8 ++--
 ...calingEventExecutorChooserFactoryTest.java | 40 +++++++++++++++++--
 2 files changed, 41 insertions(+), 7 deletions(-)

diff --git a/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java b/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java
index 6f0bdf67d3..5b67067206 100644
--- a/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java
+++ b/common/src/main/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactory.java
@@ -442,11 +442,11 @@ public final class AutoScalingEventExecutorChooserFactory implements EventExecut
                                 // Reset cycles upon suspension so it doesn't get immediately re-suspended on wake-up.
                                 idleChild.resetBusyCycles();
                                 idleChild.resetIdleCycles();
-                            } else {
-                                // If failed to suspend, we add it to the paused children to later be able to suspend it
-                                toPause.add(idleChild);
+                                changed = true;
                             }
-                            changed = true;
+                            // If it can't be suspended (e.g. suspension is not supported) it has no channels to drain,
+                            // so keep it active and retry in the next cycle. Pausing it would take it out of rotation
+                            // without any way to ever suspend it.
                         }
                     }
                     // If we have extra threads to remove then we can pause the executors that are idle
diff --git a/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java b/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java
index 0aba34f7bc..2db2b5af66 100644
--- a/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java
+++ b/common/src/test/java/io/netty/util/concurrent/AutoScalingEventExecutorChooserFactoryTest.java
@@ -54,7 +54,11 @@ public class AutoScalingEventExecutorChooserFactoryTest {
         private final AtomicInteger registeredChannels = new AtomicInteger(0);

         TestEventExecutor(EventExecutorGroup parent, Executor executor) {
-            super(parent, executor, true, true, DEFAULT_MAX_PENDING_EXECUTOR_TASKS,
+            this(parent, executor, true);
+        }
+
+        TestEventExecutor(EventExecutorGroup parent, Executor executor, boolean supportSuspension) {
+            super(parent, executor, true, supportSuspension, DEFAULT_MAX_PENDING_EXECUTOR_TASKS,
                   RejectedExecutionHandlers.reject());
         }

@@ -115,17 +119,23 @@ public class AutoScalingEventExecutorChooserFactoryTest {
         private static final Object[] ARGS = new Object[0];

         TestEventExecutorGroup(int minThreads, int maxThreads, long checkPeriod, TimeUnit unit) {
+            this(minThreads, maxThreads, checkPeriod, unit, true);
+        }
+
+        TestEventExecutorGroup(int minThreads, int maxThreads, long checkPeriod, TimeUnit unit,
+                               boolean supportSuspension) {
             super(maxThreads,
                   new ThreadPerTaskExecutor(Executors.defaultThreadFactory()),
                   new AutoScalingEventExecutorChooserFactory(
                           minThreads, maxThreads, checkPeriod, unit, 0.4, 0.6,
                           maxThreads, maxThreads, 2),
-                  ARGS);
+                  // newChild(...) is called from the super constructor, so pass the flag as an argument.
+                  supportSuspension ? ARGS : new Object[] { Boolean.FALSE });
         }

         @Override
         protected EventExecutor newChild(Executor executor, Object... args) {
-            return new TestEventExecutor(this, executor);
+            return new TestEventExecutor(this, executor, args.length == 0);
         }
     }

@@ -426,6 +436,30 @@ public class AutoScalingEventExecutorChooserFactoryTest {
         }
     }

+    @Test
+    @Timeout(30)
+    void testIdleExecutorsThatCanNotBeSuspendedStayActive() throws InterruptedException {
+        final int maxThreads = 3;
+        final int timeWindowMs = 20;
+        TestEventExecutorGroup group = new TestEventExecutorGroup(1, maxThreads,
+                timeWindowMs, TimeUnit.MILLISECONDS, false);
+        try {
+            startAllExecutors(group);
+            // Without registered channels there is nothing to drain, so executors that fail to suspend must not be
+            // taken out of rotation. Give the monitor plenty of cycles (the patience is 2 cycles) to prove it.
+            Thread.sleep(timeWindowMs * 20);
+
+            assertEquals(maxThreads, group.activeExecutorCount());
+            Set<EventExecutor> chosen = new HashSet<>();
+            for (int i = 0; i < 4 * maxThreads; i++) {
+                chosen.add(group.next());
+            }
+            assertEquals(maxThreads, chosen.size());
+        } finally {
+            group.shutdownGracefully().syncUninterruptibly();
+        }
+    }
+
     @Test
     @Timeout(60)
     void testConcurrentNextWithAllExecutorsPausedKeepsStateConsistent() throws Exception {
--
2.54.0 (Apple Git-157)

If you agree feel free to apply and push

All reactions

Sorry, something went wrong.

Uh oh!

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

@normanmaurer normanmaurer added this to the 4.2.21.Final milestone Nov 11, 2026
@chrisvest chrisvest modified the milestones: 4.2.21.Final, 4.2.22.Final Nov 16, 2026
@normanmaurer

normanmaurer commented Nov 26, 2026

Copy link
Copy Markdown
Member

@isaacrivriv ping

All reactions

Sorry, something went wrong.

Uh oh!

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@franz1981 franz1981 franz1981 approved these changes
@normanmaurer normanmaurer Awaiting requested review from normanmaurer

Uh oh!

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

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

4.2.22.Final

Development

Successfully merging this pull request may close these issues.

AutoScalingEventExecutorChooserFactory not properly scaling threads

Uh oh!

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

5 participants

@isaacrivriv @franz1981 @normanmaurer @georgebanasios @chrisvest
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.