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 — Round up the NIO select timeout again to not busy spin (#18137) · netty/netty@06518dc

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • transport/src
    • main/java/io/netty/channel/nio
      • NioIoHandler.java
    • test/java/io/netty/channel/nio
      • NioIoHandlerTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎transport/src/main/java/io/netty/channel/nio/NioIoHandler.java‎

Copy file name to clipboardExpand all lines: transport/src/main/java/io/netty/channel/nio/NioIoHandler.java
+11-4Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -721,16 +721,23 @@ private void select(IoHandlerContext runner, boolean oldWakenUp) throws IOExcept
721721
}
722722
}
723723

724-
private static long millisBeforeDeadline(long selectDeadLineNanos, long currentTimeNanos) {
724+
/**
725+
* Returns the timeout in milliseconds for {@link Selector#select(long)} when the next scheduled task is due after
726+
* the given deadline. The value is rounded up, so it is only {@code 0} if the deadline is less than 5 microseconds
727+
* away. Rounding to the nearest millisecond would return {@code 0} for a deadline less than 0.5 ms away, and
728+
* the event loop would then call {@link Selector#selectNow()} in a loop, burning CPU, until the deadline
729+
* is reached.
730+
*/
731+
static long millisBeforeDeadline(long selectDeadLineNanos, long currentTimeNanos) {
725732
assert selectDeadLineNanos != Long.MAX_VALUE;
726733
long nanosBeforeDeadline = selectDeadLineNanos - currentTimeNanos;
727734
// Prevent overflow when adding the rounding bias:
728735
// if we don't do this, it would appear as the deadline is already reached!
729-
if (nanosBeforeDeadline >= Long.MAX_VALUE - 500_000L) {
736+
if (nanosBeforeDeadline >= Long.MAX_VALUE - 995_000L) {
730737
return Long.MAX_VALUE / 1_000_000L;
731738
}
732-
// Add 500_000 to round up to the nearest millisecond.
733-
return (nanosBeforeDeadline + 500_000L) / 1_000_000L;
739+
// Add 995_000 to round up to the next millisecond, the timeout is only 0 if the deadline is within 5 micros.
740+
return (nanosBeforeDeadline + 995_000L) / 1_000_000L;
734741
}
735742

736743
int selectNow() throws IOException {
Collapse file

‎transport/src/test/java/io/netty/channel/nio/NioIoHandlerTest.java‎

Copy file name to clipboardExpand all lines: transport/src/test/java/io/netty/channel/nio/NioIoHandlerTest.java
+84Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,10 @@
3131
import java.nio.channels.spi.SelectorProvider;
3232
import java.util.Queue;
3333
import java.util.concurrent.ConcurrentLinkedQueue;
34+
import java.util.concurrent.TimeUnit;
3435
import java.util.concurrent.atomic.AtomicBoolean;
3536

37+
import static org.junit.jupiter.api.Assertions.assertEquals;
3638
import static org.junit.jupiter.api.Assertions.assertTrue;
3739

3840
public class NioIoHandlerTest {
@@ -133,4 +135,86 @@ protected void handle(ServerSocketChannel channel, SelectionKey key) {
133135
handler.prepareToDestroy();
134136
handler.destroy();
135137
}
138+
139+
@Test
140+
void testMillisBeforeDeadlineRoundsUp() {
141+
long now = 1_000_000_000L;
142+
// The timeout is only 0 if the deadline is within 5 microseconds, or already reached.
143+
assertEquals(0, NioIoHandler.millisBeforeDeadline(now - 1, now));
144+
assertEquals(0, NioIoHandler.millisBeforeDeadline(now, now));
145+
assertEquals(0, NioIoHandler.millisBeforeDeadline(now + 1, now));
146+
assertEquals(0, NioIoHandler.millisBeforeDeadline(now + 4_999, now));
147+
// Everything from 5 microseconds up to 1 ms is rounded up to 1 ms, also less than 0.5 ms.
148+
// After that the timeout grows by 1 ms every ms, 5 microseconds early.
149+
assertEquals(1, NioIoHandler.millisBeforeDeadline(now + 5_000, now));
150+
assertEquals(1, NioIoHandler.millisBeforeDeadline(now + 100_000, now));
151+
assertEquals(1, NioIoHandler.millisBeforeDeadline(now + 499_999, now));
152+
assertEquals(1, NioIoHandler.millisBeforeDeadline(now + 500_000, now));
153+
assertEquals(1, NioIoHandler.millisBeforeDeadline(now + 999_999, now));
154+
assertEquals(1, NioIoHandler.millisBeforeDeadline(now + 1_000_000, now));
155+
assertEquals(1, NioIoHandler.millisBeforeDeadline(now + 1_004_999, now));
156+
assertEquals(2, NioIoHandler.millisBeforeDeadline(now + 1_005_000, now));
157+
assertEquals(2, NioIoHandler.millisBeforeDeadline(now + 2_004_999, now));
158+
assertEquals(3, NioIoHandler.millisBeforeDeadline(now + 2_005_000, now));
159+
assertEquals(1_000, NioIoHandler.millisBeforeDeadline(now + TimeUnit.SECONDS.toNanos(1), now));
160+
}
161+
162+
@Test
163+
void testMillisBeforeDeadlineDoesNotOverflow() {
164+
long maxMillis = Long.MAX_VALUE / 1_000_000L;
165+
// Far deadlines are capped, they must never look like a deadline that is already reached.
166+
assertEquals(maxMillis, NioIoHandler.millisBeforeDeadline(Long.MAX_VALUE - 1, 0));
167+
assertEquals(maxMillis, NioIoHandler.millisBeforeDeadline(Long.MAX_VALUE - 995_000L, 0));
168+
assertEquals(maxMillis, NioIoHandler.millisBeforeDeadline(Long.MAX_VALUE - 995_001L, 0));
169+
assertEquals(maxMillis, NioIoHandler.millisBeforeDeadline(Long.MAX_VALUE - 1_000_000L, 0));
170+
assertTrue(NioIoHandler.millisBeforeDeadline(Long.MAX_VALUE - 10_000_000L, 0) > 0);
171+
}
172+
173+
@Test
174+
void testNoBusySpinIfDeadlineIsLessThanHalfAMillisecondAway() throws Exception {
175+
final long[] deadline = new long[1];
176+
final ThreadAwareExecutor executor = new ThreadAwareExecutor() {
177+
@Override
178+
public boolean isExecutorThread(Thread thread) {
179+
return true;
180+
}
181+
182+
@Override
183+
public void execute(Runnable command) {
184+
throw new UnsupportedOperationException();
185+
}
186+
};
187+
IoHandlerContext context = new IoHandlerContext() {
188+
@Override
189+
public boolean canBlock() {
190+
return true;
191+
}
192+
193+
@Override
194+
public long delayNanos(long currentTimeNanos) {
195+
return Math.max(0, deadline[0] - currentTimeNanos);
196+
}
197+
198+
@Override
199+
public long deadlineNanos() {
200+
return deadline[0];
201+
}
202+
};
203+
IoHandler handler = NioIoHandler.newFactory().newHandler(executor);
204+
try {
205+
deadline[0] = System.nanoTime() + TimeUnit.MICROSECONDS.toNanos(300);
206+
// An event loop calls run(...) again as long as the scheduled task is not due. If run(...) returns
207+
// without sleeping, as it did when the timeout was rounded to the nearest millisecond, this loops
208+
// thousands of times until the deadline is reached.
209+
int iterations = 0;
210+
while (System.nanoTime() < deadline[0]) {
211+
handler.run(context);
212+
iterations++;
213+
}
214+
assertTrue(iterations <= 3, "run(...) returned " + iterations + " times before the deadline");
215+
} finally {
216+
handler.prepareToDestroy();
217+
handler.destroy();
218+
}
219+
}
136220
}

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.