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 — Prevent ManualEventLoop to block on a racy task submission · netty/netty@e112199

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • transport-classes-epoll/src/main/java/io/netty/channel/epoll
    • EpollIoHandler.java
  • transport-native-epoll/src/test/java/io/netty/channel/epoll
    • ManualEventLoopTest.java
  • transport/src/main/java/io/netty/channel
    • ManualIoEventLoop.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollIoHandler.java‎

Copy file name to clipboardExpand all lines: transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollIoHandler.java
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public class EpollIoHandler implements IoHandler {
6161
}
6262

6363
// Pick a number that no task could have previously used.
64-
private long prevDeadlineNanos = nanoTime() - 1;
64+
private long prevDeadlineNanos = NONE;
6565
private FileDescriptor epollFd;
6666
private FileDescriptor eventFd;
6767
private FileDescriptor timerFd;
Collapse file

‎transport-native-epoll/src/test/java/io/netty/channel/epoll/ManualEventLoopTest.java‎

Copy file name to clipboard
+252Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
/*
2+
* Copyright 2025 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.epoll;
17+
18+
import io.netty.channel.IoEventLoop;
19+
import io.netty.channel.IoEventLoopGroup;
20+
import io.netty.channel.IoHandlerFactory;
21+
import io.netty.channel.ManualIoEventLoop;
22+
import io.netty.channel.MultiThreadIoEventLoopGroup;
23+
import io.netty.channel.nio.NioIoHandler;
24+
import io.netty.util.concurrent.Future;
25+
import org.junit.jupiter.api.RepeatedTest;
26+
import org.junit.jupiter.api.Test;
27+
import org.junit.jupiter.api.Timeout;
28+
29+
import java.util.Queue;
30+
import java.util.concurrent.ConcurrentLinkedQueue;
31+
import java.util.concurrent.CountDownLatch;
32+
import java.util.concurrent.CyclicBarrier;
33+
import java.util.concurrent.ExecutionException;
34+
import java.util.concurrent.Executor;
35+
import java.util.concurrent.RejectedExecutionException;
36+
import java.util.concurrent.TimeUnit;
37+
import java.util.concurrent.atomic.AtomicLong;
38+
import java.util.function.Consumer;
39+
40+
@Timeout(value = 5)
41+
public class ManualEventLoopTest {
42+
43+
@Test
44+
void firstRacySubmissionMissWakeupEpoll() throws Exception {
45+
racySubmissionMissWakeup(EpollIoHandler.newFactory(), 1);
46+
}
47+
48+
@Test
49+
void secondRacySubmissionMissWakeupEpoll() throws Exception {
50+
racySubmissionMissWakeup(EpollIoHandler.newFactory(), 2);
51+
}
52+
53+
@Test
54+
void firstRacyOtherSubmissionMissWakeupEpoll() throws Exception {
55+
racyOtherSubmissionMissWakeup(EpollIoHandler.newFactory(), 1);
56+
}
57+
58+
@Test
59+
void secondRacyOtherSubmissionMissWakeupEpoll() throws Exception {
60+
racyOtherSubmissionMissWakeup(EpollIoHandler.newFactory(), 2);
61+
}
62+
63+
void racySubmissionMissWakeup(IoHandlerFactory handlerFactory, long canBlockAttempt)
64+
throws Exception {
65+
CyclicBarrier waitBeforeSubmittingTask = new CyclicBarrier(2);
66+
CountDownLatch taskSubmitted = new CountDownLatch(1);
67+
AtomicLong canBlock = new AtomicLong(0);
68+
ManualMultithreadedIoEventLoopGroup group = new ManualMultithreadedIoEventLoopGroup(handlerFactory) {
69+
@Override
70+
protected void beforeCanBlock(Executor executor) {
71+
// this should be called when canBlock is called after setting the wakeup flag!
72+
if (canBlock.incrementAndGet() == canBlockAttempt) {
73+
try {
74+
waitBeforeSubmittingTask.await();
75+
} catch (Throwable ignore) {
76+
//
77+
}
78+
try {
79+
taskSubmitted.await();
80+
} catch (InterruptedException e) {
81+
throw new RuntimeException(e);
82+
}
83+
}
84+
}
85+
};
86+
waitBeforeSubmittingTask.await();
87+
// the wakeup flag is set already so no event fd wakeup will be triggered!!!!
88+
Future<?> submitted = group.submit(() -> {
89+
});
90+
// unblock canBlock
91+
taskSubmitted.countDown();
92+
submitted.get();
93+
group.shutdownGracefully(0, 0, TimeUnit.SECONDS).get();
94+
}
95+
96+
void racyOtherSubmissionMissWakeup(IoHandlerFactory handlerFactory, long canBlockAttempt)
97+
throws Exception {
98+
CyclicBarrier waitBeforeSubmittingTask = new CyclicBarrier(2);
99+
CountDownLatch taskSubmitted = new CountDownLatch(1);
100+
AtomicLong canBlock = new AtomicLong(0);
101+
ManualMultithreadedIoEventLoopGroup group = new ManualMultithreadedIoEventLoopGroup(handlerFactory) {
102+
@Override
103+
protected void beforeCanBlock(Executor executor) {
104+
// this should be called when canBlock is called after setting the wakeup flag!
105+
if (canBlock.incrementAndGet() == canBlockAttempt) {
106+
try {
107+
waitBeforeSubmittingTask.await();
108+
} catch (Throwable ignore) {
109+
//
110+
}
111+
try {
112+
taskSubmitted.await();
113+
} catch (InterruptedException e) {
114+
throw new RuntimeException(e);
115+
}
116+
}
117+
}
118+
};
119+
waitBeforeSubmittingTask.await();
120+
CountDownLatch completed = new CountDownLatch(1);
121+
group.ioEventLoopRunner.execute(completed::countDown);
122+
taskSubmitted.countDown();
123+
completed.await();
124+
group.shutdownGracefully(0, 0, TimeUnit.SECONDS).get();
125+
}
126+
127+
@RepeatedTest(value = 100, failureThreshold = 1)
128+
void testTightShutodownEpoll() throws InterruptedException, ExecutionException {
129+
ManualMultithreadedIoEventLoopGroup group = new ManualMultithreadedIoEventLoopGroup(
130+
EpollIoHandler.newFactory());
131+
group.shutdownGracefully(0, 0, TimeUnit.SECONDS).get();
132+
}
133+
134+
@RepeatedTest(value = 100, failureThreshold = 1)
135+
void testTightShutodownNIO() throws InterruptedException, ExecutionException {
136+
ManualMultithreadedIoEventLoopGroup group = new ManualMultithreadedIoEventLoopGroup(
137+
NioIoHandler.newFactory());
138+
group.shutdownGracefully(0, 0, TimeUnit.SECONDS).get();
139+
}
140+
141+
@Test
142+
void testTightSubmissionsEpoll() throws ExecutionException, InterruptedException {
143+
ManualMultithreadedIoEventLoopGroup group = new ManualMultithreadedIoEventLoopGroup(
144+
EpollIoHandler.newFactory());
145+
for (int i = 0; i < 1000; i++) {
146+
group.submit(() -> {
147+
}).get();
148+
}
149+
group.shutdownGracefully(0, 0, TimeUnit.SECONDS).get();
150+
}
151+
152+
@Test
153+
void testTightSubmissionsNIO() throws ExecutionException, InterruptedException {
154+
ManualMultithreadedIoEventLoopGroup group = new ManualMultithreadedIoEventLoopGroup(
155+
NioIoHandler.newFactory());
156+
for (int i = 0; i < 1000; i++) {
157+
group.submit(() -> {
158+
}).get();
159+
}
160+
group.shutdownGracefully(0, 0, TimeUnit.SECONDS).get();
161+
}
162+
163+
public static class ManualMultithreadedIoEventLoopGroup extends MultiThreadIoEventLoopGroup {
164+
165+
private ManualIoEventLoopRunner ioEventLoopRunner;
166+
private Consumer<ManualIoEventLoopRunner> beforeCanBlock;
167+
168+
public ManualMultithreadedIoEventLoopGroup(IoHandlerFactory ioHandlerFactory) {
169+
super(1, ioHandlerFactory);
170+
}
171+
172+
@Override
173+
protected IoEventLoop newChild(Executor executor, IoHandlerFactory ioHandlerFactory, Object... args) {
174+
this.ioEventLoopRunner = new ManualIoEventLoopRunner(this, ioHandlerFactory,
175+
executor, this::beforeCanBlock);
176+
return ioEventLoopRunner.ioEventLoop;
177+
}
178+
179+
protected void beforeCanBlock(Executor executor) {
180+
}
181+
182+
private static class ManualIoEventLoopRunner implements Executor {
183+
184+
private final ManualIoEventLoop ioEventLoop;
185+
private final Queue<Runnable> otherTasks = new ConcurrentLinkedQueue<>();
186+
187+
ManualIoEventLoopRunner(IoEventLoopGroup parent, IoHandlerFactory factory,
188+
Executor executor, Consumer<Executor> beforeCanBlock) {
189+
this.ioEventLoop = new ManualIoEventLoop(parent, null, factory) {
190+
@Override
191+
protected boolean canBlock() {
192+
if (beforeCanBlock != null) {
193+
beforeCanBlock.accept(ManualIoEventLoopRunner.this);
194+
}
195+
return otherTasks.isEmpty();
196+
}
197+
};
198+
CountDownLatch started = new CountDownLatch(1);
199+
executor.execute(() -> {
200+
ioEventLoop.setOwningThread(Thread.currentThread());
201+
// it would force a first init
202+
ioEventLoop.runNow();
203+
started.countDown();
204+
mainLoop();
205+
});
206+
try {
207+
started.await();
208+
} catch (InterruptedException e) {
209+
Thread.currentThread().interrupt();
210+
throw new RuntimeException(e);
211+
}
212+
}
213+
214+
private void mainLoop() {
215+
while (!ioEventLoop.isShuttingDown()) {
216+
if (otherTasks.isEmpty()) {
217+
ioEventLoop.run(0);
218+
}
219+
Runnable otherTask = otherTasks.poll();
220+
if (otherTask != null) {
221+
safeExecute(otherTask);
222+
}
223+
}
224+
while (!ioEventLoop.isTerminated() || !otherTasks.isEmpty()) {
225+
ioEventLoop.runNow();
226+
Runnable otherTask = otherTasks.poll();
227+
if (otherTask != null) {
228+
safeExecute(otherTask);
229+
}
230+
}
231+
}
232+
233+
private void safeExecute(Runnable task) {
234+
try {
235+
task.run();
236+
} catch (Throwable ignore) {
237+
//
238+
}
239+
}
240+
241+
public void execute(Runnable otherTask) {
242+
otherTasks.add(otherTask);
243+
if (ioEventLoop.isShutdown()) {
244+
if (otherTasks.remove(otherTask)) {
245+
throw new RejectedExecutionException("Event loop shut down");
246+
}
247+
}
248+
ioEventLoop.wakeup();
249+
}
250+
}
251+
}
252+
}
Collapse file

‎transport/src/main/java/io/netty/channel/ManualIoEventLoop.java‎

Copy file name to clipboardExpand all lines: transport/src/main/java/io/netty/channel/ManualIoEventLoop.java
+25-8Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
* {@link IoEventLoop} to also do other work. Care must be taken that the {@link #runNow() or
4848
* {@link #waitAndRun()}} methods are called in a timely fashion.
4949
*/
50-
public final class ManualIoEventLoop extends AbstractScheduledEventExecutor implements IoEventLoop {
50+
public class ManualIoEventLoop extends AbstractScheduledEventExecutor implements IoEventLoop {
5151
private static final int ST_STARTED = 0;
5252
private static final int ST_SHUTTING_DOWN = 1;
5353
private static final int ST_SHUTDOWN = 2;
@@ -87,6 +87,14 @@ public long deadlineNanos() {
8787
private long lastExecutionTime;
8888
private boolean initialized;
8989

90+
/**
91+
* This allows to specify additional blocking conditions which will be used by the {@link IoHandler} to decide
92+
* whether it is allowed to block or not.
93+
*/
94+
protected boolean canBlock() {
95+
return true;
96+
}
97+
9098
/**
9199
* Create a new {@link IoEventLoop} that is owned by the user and so needs to be driven by the user with the given
92100
* {@link Thread}. This means that the user is responsible to call either {@link #runNow()} or
@@ -461,6 +469,9 @@ private void shutdown0(long quietPeriod, long timeout, int shutdownState) {
461469
}
462470

463471
if (wakeup) {
472+
// same as AbstractScheduledEventExecutor.WAKEUP_TASK
473+
taskQueue.offer(() -> {
474+
});
464475
handler.wakeup();
465476
}
466477
}
@@ -632,13 +643,14 @@ private void throwIfInEventLoop(String method) {
632643
}
633644
}
634645

635-
private final class BlockingIoHandlerContext implements IoHandlerContext {
646+
private class BlockingIoHandlerContext implements IoHandlerContext {
647+
// this is a positive amount of nanos or Long.MAX_VALUE for no limit
636648
long maxBlockingNanos = Long.MAX_VALUE;
637649

638650
@Override
639651
public boolean canBlock() {
640652
assert inEventLoop();
641-
return !hasTasks() && !hasScheduledTasks();
653+
return !hasTasks() && !hasScheduledTasks() && ManualIoEventLoop.this.canBlock();
642654
}
643655

644656
@Override
@@ -651,11 +663,16 @@ public long delayNanos(long currentTimeNanos) {
651663
public long deadlineNanos() {
652664
assert inEventLoop();
653665
long next = nextScheduledTaskDeadlineNanos();
654-
long maxDeadlineNanos = ticker.nanoTime() + maxBlockingNanos;
655-
if (next == -1) {
656-
return maxDeadlineNanos;
666+
if (maxBlockingNanos == Long.MAX_VALUE) {
667+
// next == -1? -1 : next i.e. return next
668+
return next;
669+
}
670+
long now = ticker.nanoTime();
671+
// we cannot just check Math.min as nanoTime can be negative or wrap around!
672+
if (next == -1 || next - now > maxBlockingNanos) {
673+
return now + maxBlockingNanos;
657674
}
658-
return Math.min(next, maxDeadlineNanos);
675+
return next;
659676
}
660-
};
677+
}
661678
}

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.