|
| 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 | +} |