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 — Auto-port 5.0: Avoid redundant kevent wakeups in KQueueIoHandler (#18… · netty/netty@beb54e7

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • transport-classes-kqueue/src/main/java/io/netty/channel/kqueue
    • KQueueIoHandler.java
  • transport-native-kqueue/src/test/java/io/netty/channel/kqueue
    • KQueueIoHandlerWakeupTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueIoHandler.java‎

Copy file name to clipboardExpand all lines: transport-classes-kqueue/src/main/java/io/netty/channel/kqueue/KQueueIoHandler.java
+36-48Lines changed: 36 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,11 @@
4747
*/
4848
public final class KQueueIoHandler implements IoHandler {
4949
private static final InternalLogger logger = InternalLoggerFactory.getInstance(KQueueIoHandler.class);
50-
private static final AtomicIntegerFieldUpdater<KQueueIoHandler> WAKEN_UP_UPDATER =
51-
AtomicIntegerFieldUpdater.newUpdater(KQueueIoHandler.class, "wakenUp");
50+
private static final AtomicIntegerFieldUpdater<KQueueIoHandler> WAKEUP_STATE_UPDATER =
51+
AtomicIntegerFieldUpdater.newUpdater(KQueueIoHandler.class, "wakeupState");
52+
private static final int AWAKE = 0;
53+
private static final int SELECTING = 1;
54+
private static final int WAKEUP_REQUESTED = 2;
5255
private static final int KQUEUE_WAKE_UP_IDENT = 0;
5356
// `kqueue()` may return EINVAL when a large number such as Integer.MAX_VALUE is specified as timeout.
5457
// 24 hours would be a large enough value.
@@ -76,7 +79,13 @@ public int get() throws Exception {
7679
private final LongObjectMap<DefaultKqueueIoRegistration> registrations = new LongObjectHashMap<>(4096);
7780
private long nextId;
7881

79-
private volatile int wakenUp;
82+
// AWAKE: the event loop is running and will not block without checking for work first.
83+
// SELECTING: the event loop is about to block in (or is blocked in) kevent(...).
84+
// WAKEUP_REQUESTED: another thread asked for a wakeup. If the event loop was SELECTING the user event was
85+
// triggered as well. Otherwise the request is only remembered and makes the next
86+
// kevent(...) non-blocking, which avoids a syscall for every task submitted to a running
87+
// event loop. A wakeup does not always come with a queued task (for example, suspension).
88+
private volatile int wakeupState = AWAKE;
8089

8190
private long generateNextId() {
8291
boolean reset = false;
@@ -147,8 +156,10 @@ private KQueueIoHandler(ThreadAwareExecutor executor, int maxEvents, SelectStrat
147156

148157
@Override
149158
public void wakeup() {
150-
if (!executor.isExecutorThread(Thread.currentThread())
151-
&& WAKEN_UP_UPDATER.compareAndSet(this, 0, 1)) {
159+
if (!executor.isExecutorThread(Thread.currentThread()) && wakeupState != WAKEUP_REQUESTED
160+
&& WAKEUP_STATE_UPDATER.getAndSet(this, WAKEUP_REQUESTED) == SELECTING) {
161+
// Only needed if the event loop is about to block or already blocked. In every other state it will
162+
// see the request (or the work that came with it) before it blocks the next time.
152163
wakeup0();
153164
}
154165
}
@@ -159,19 +170,28 @@ private void wakeup0() {
159170
// So it is not very practical to assert the return value is always >= 0.
160171
}
161172

162-
private int kqueueWait(IoHandlerContext context, boolean oldWakeup) throws IOException {
163-
// If a task was submitted when wakenUp value was 1, the task didn't get a chance to produce wakeup event.
164-
// So we need to check task queue again before calling kqueueWait. If we don't, the task might be pended
165-
// until kqueueWait was timed out. It might be pended until idle timeout if IdleStateHandler existed
166-
// in pipeline.
167-
if (oldWakeup && !context.canBlock()) {
173+
private int kqueueWait(IoHandlerContext context) throws IOException {
174+
if (!WAKEUP_STATE_UPDATER.compareAndSet(this, AWAKE, SELECTING)) {
175+
// A wakeup was requested while we were awake. It was only remembered, so consume it with a
176+
// non-blocking kevent(...) and let the caller look for the work that came with it.
177+
WAKEUP_STATE_UPDATER.lazySet(this, AWAKE);
168178
return kqueueWaitNow();
169179
}
180+
try {
181+
// Check again after publishing SELECTING. A task submitted before that is seen here and one submitted
182+
// later will trigger the user event. Without this the task might be pended until kqueueWait was timed
183+
// out. It might be pended until idle timeout if IdleStateHandler existed in pipeline.
184+
if (!context.canBlock() || wakeupState == WAKEUP_REQUESTED) {
185+
return kqueueWaitNow();
186+
}
170187

171-
long totalDelay = context.delayNanos(System.nanoTime());
172-
int delaySeconds = (int) min(totalDelay / 1000000000L, KQUEUE_MAX_TIMEOUT_SECONDS);
173-
int delayNanos = (int) (totalDelay % 1000000000L);
174-
return kqueueWait(delaySeconds, delayNanos);
188+
long totalDelay = context.delayNanos(System.nanoTime());
189+
int delaySeconds = (int) min(totalDelay / 1000000000L, KQUEUE_MAX_TIMEOUT_SECONDS);
190+
int delayNanos = (int) (totalDelay % 1000000000L);
191+
return kqueueWait(delaySeconds, delayNanos);
192+
} finally {
193+
WAKEUP_STATE_UPDATER.lazySet(this, AWAKE);
194+
}
175195
}
176196

177197
private int kqueueWaitNow() throws IOException {
@@ -229,39 +249,7 @@ public int run(IoHandlerContext context) {
229249
// fall-through to SELECT since the busy-wait is not supported with kqueue
230250

231251
case SelectStrategy.SELECT:
232-
strategy = kqueueWait(context, WAKEN_UP_UPDATER.getAndSet(this, 0) == 1);
233-
234-
// 'wakenUp.compareAndSet(false, true)' is always evaluated
235-
// before calling 'selector.wakeup()' to reduce the wake-up
236-
// overhead. (Selector.wakeup() is an expensive operation.)
237-
//
238-
// However, there is a race condition in this approach.
239-
// The race condition is triggered when 'wakenUp' is set to
240-
// true too early.
241-
//
242-
// 'wakenUp' is set to true too early if:
243-
// 1) Selector is waken up between 'wakenUp.set(false)' and
244-
// 'selector.select(...)'. (BAD)
245-
// 2) Selector is waken up between 'selector.select(...)' and
246-
// 'if (wakenUp.get()) { ... }'. (OK)
247-
//
248-
// In the first case, 'wakenUp' is set to true and the
249-
// following 'selector.select(...)' will wake up immediately.
250-
// Until 'wakenUp' is set to false again in the next round,
251-
// 'wakenUp.compareAndSet(false, true)' will fail, and therefore
252-
// any attempt to wake up the Selector will fail, too, causing
253-
// the following 'selector.select(...)' call to block
254-
// unnecessarily.
255-
//
256-
// To fix this problem, we wake up the selector again if wakenUp
257-
// is true immediately after selector.select(...).
258-
// It is inefficient in that it wakes up the selector for both
259-
// the first case (BAD - wake-up required) and the second case
260-
// (OK - no wake-up required).
261-
262-
if (wakenUp == 1) {
263-
wakeup0();
264-
}
252+
strategy = kqueueWait(context);
265253
// fall-through
266254
default:
267255
}
Collapse file

‎transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueIoHandlerWakeupTest.java‎

Copy file name to clipboard
+224Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
/*
2+
* Copyright 2026 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. You may obtain a copy of the License at:
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
package io.netty.channel.kqueue;
17+
18+
import io.netty.channel.IoHandler;
19+
import io.netty.channel.IoHandlerContext;
20+
import io.netty.channel.unix.FileDescriptor;
21+
import io.netty.util.concurrent.ThreadAwareExecutor;
22+
import org.junit.jupiter.api.AfterEach;
23+
import org.junit.jupiter.api.BeforeAll;
24+
import org.junit.jupiter.api.BeforeEach;
25+
import org.junit.jupiter.api.Test;
26+
import org.junit.jupiter.api.Timeout;
27+
28+
import java.lang.reflect.Field;
29+
import java.util.Queue;
30+
import java.util.concurrent.CompletableFuture;
31+
import java.util.concurrent.ConcurrentLinkedQueue;
32+
import java.util.concurrent.ExecutorService;
33+
import java.util.concurrent.Executors;
34+
import java.util.concurrent.TimeUnit;
35+
import java.util.concurrent.atomic.AtomicLong;
36+
import java.util.function.BooleanSupplier;
37+
38+
import static org.assertj.core.api.Assertions.assertThat;
39+
import static org.junit.jupiter.api.Assumptions.assumeTrue;
40+
41+
public class KQueueIoHandlerWakeupTest {
42+
43+
private ExecutorService loopExecutor;
44+
private volatile Thread loopThread;
45+
private KQueueIoHandler handler;
46+
47+
@BeforeAll
48+
public static void loadJNI() {
49+
assumeTrue(KQueue.isAvailable());
50+
}
51+
52+
@BeforeEach
53+
public void setUp() throws Exception {
54+
loopExecutor = Executors.newSingleThreadExecutor();
55+
// Pin the "event loop thread" before creating the handler, so wakeup() calls made from any other thread
56+
// are treated as coming from outside the event loop.
57+
loopThread = loopExecutor.submit(Thread::currentThread).get(5, TimeUnit.SECONDS);
58+
ThreadAwareExecutor executor = new ThreadAwareExecutor() {
59+
@Override
60+
public boolean isExecutorThread(Thread thread) {
61+
return thread == loopThread;
62+
}
63+
64+
@Override
65+
public void execute(Runnable command) {
66+
throw new UnsupportedOperationException();
67+
}
68+
};
69+
IoHandler h = KQueueIoHandler.newFactory().newHandler(executor);
70+
handler = (KQueueIoHandler) h;
71+
}
72+
73+
@AfterEach
74+
public void tearDown() throws Exception {
75+
try {
76+
loopExecutor.submit(() -> handler.destroy()).get(5, TimeUnit.SECONDS);
77+
} finally {
78+
loopExecutor.shutdownNow();
79+
}
80+
}
81+
82+
@Test
83+
@Timeout(30)
84+
public void testWakeupWhileAwakeDoesNotTriggerUserEvent() throws Exception {
85+
// The event loop is not blocked in kevent(...) so there is nothing to wake up. It will find the work that
86+
// comes with a wakeup the next time it is about to block, so the (expensive) user event must not be
87+
// triggered.
88+
fromAnotherThread(handler::wakeup);
89+
assertThat(pendingEvents()).isZero();
90+
91+
// The remembered request must not make us block forever, it is consumed by the next run.
92+
assertThat(runOnLoopThread(blockingContext(null))).succeedsWithin(10, TimeUnit.SECONDS);
93+
assertThat(pendingEvents()).isZero();
94+
}
95+
96+
@Test
97+
@Timeout(30)
98+
public void testWakeupWhileSelectingTriggersUserEvent() throws Exception {
99+
// Request the wakeup after the event loop decided that it is going to block. Nothing else will wake it up
100+
// as nothing is scheduled and there is no I/O, so run() only returns if the user event was triggered.
101+
assertThat(runOnLoopThread(blockingContext(() -> fromAnotherThread(handler::wakeup))))
102+
.succeedsWithin(10, TimeUnit.SECONDS);
103+
assertThat(pendingEvents()).isZero();
104+
}
105+
106+
@Test
107+
@Timeout(30)
108+
public void testWakeupWithoutTaskIsNeverLost() throws Exception {
109+
// A wakeup is not always accompanied by a task (for example, suspension). Whatever the state of the event
110+
// loop is, it needs to notice the request and may not block forever.
111+
final int iterations = 20_000;
112+
final AtomicLong request = new AtomicLong();
113+
final AtomicLong seen = new AtomicLong();
114+
final IoHandlerContext blocking = blockingContext(null);
115+
116+
CompletableFuture<Void> loop = runOnLoopThread(() -> {
117+
while (seen.get() < iterations) {
118+
handler.run(blocking);
119+
seen.set(request.get());
120+
}
121+
});
122+
123+
for (long i = 1; i <= iterations; i++) {
124+
request.set(i);
125+
handler.wakeup();
126+
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
127+
while (seen.get() < i) {
128+
assertThat(System.nanoTime() - deadline).as("wakeup %s was lost", i).isNegative();
129+
Thread.yield();
130+
}
131+
}
132+
assertThat(loop).succeedsWithin(10, TimeUnit.SECONDS);
133+
}
134+
135+
@Test
136+
@Timeout(60)
137+
public void testTasksFromMultipleThreadsAreNeverLost() throws Exception {
138+
final int producers = 4;
139+
final int tasksPerProducer = 50_000;
140+
final Queue<Object> queue = new ConcurrentLinkedQueue<>();
141+
final IoHandlerContext context = context(queue::isEmpty, null);
142+
143+
CompletableFuture<Void> loop = runOnLoopThread(() -> {
144+
int processed = 0;
145+
while (processed < producers * tasksPerProducer) {
146+
handler.run(context);
147+
while (queue.poll() != null) {
148+
processed++;
149+
}
150+
}
151+
});
152+
153+
ExecutorService producerExecutor = Executors.newFixedThreadPool(producers);
154+
try {
155+
for (int p = 0; p < producers; p++) {
156+
producerExecutor.execute(() -> {
157+
for (int i = 0; i < tasksPerProducer; i++) {
158+
queue.add(this);
159+
handler.wakeup();
160+
}
161+
});
162+
}
163+
assertThat(loop).succeedsWithin(30, TimeUnit.SECONDS);
164+
} finally {
165+
producerExecutor.shutdownNow();
166+
}
167+
}
168+
169+
/**
170+
* Returns the number of events that are ready in the kqueue of the handler, which consumes them.
171+
*/
172+
private int pendingEvents() throws Exception {
173+
Field field = KQueueIoHandler.class.getDeclaredField("kqueueFd");
174+
field.setAccessible(true);
175+
int kqueueFd = ((FileDescriptor) field.get(handler)).intValue();
176+
KQueueEventArray changeList = new KQueueEventArray(4);
177+
KQueueEventArray eventList = new KQueueEventArray(4);
178+
try {
179+
return Native.keventWait(kqueueFd, changeList, eventList, 0, 0);
180+
} finally {
181+
changeList.free();
182+
eventList.free();
183+
}
184+
}
185+
186+
private CompletableFuture<Void> runOnLoopThread(IoHandlerContext context) {
187+
return runOnLoopThread(() -> handler.run(context));
188+
}
189+
190+
private CompletableFuture<Void> runOnLoopThread(Runnable task) {
191+
return CompletableFuture.runAsync(task, loopExecutor);
192+
}
193+
194+
private static void fromAnotherThread(Runnable task) {
195+
assertThat(CompletableFuture.runAsync(task)).succeedsWithin(10, TimeUnit.SECONDS);
196+
}
197+
198+
private static IoHandlerContext blockingContext(Runnable onDelayNanos) {
199+
return context(() -> true, onDelayNanos);
200+
}
201+
202+
private static IoHandlerContext context(BooleanSupplier canBlock, Runnable onDelayNanos) {
203+
return new IoHandlerContext() {
204+
@Override
205+
public boolean canBlock() {
206+
return canBlock.getAsBoolean();
207+
}
208+
209+
@Override
210+
public long delayNanos(long currentTimeNanos) {
211+
// Called after the event loop decided to block.
212+
if (onDelayNanos != null) {
213+
onDelayNanos.run();
214+
}
215+
return Long.MAX_VALUE;
216+
}
217+
218+
@Override
219+
public long deadlineNanos() {
220+
return -1;
221+
}
222+
};
223+
}
224+
}

0 commit comments

Comments
0 (0)
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.