1 /*
2 * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package sun.nio.ch;
26
27 import java.io.IOException;
28 import java.io.UncheckedIOException;
29 import java.lang.ref.Reference;
30 import java.util.Arrays;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Objects;
34 import java.util.Set;
35 import java.util.concurrent.ConcurrentHashMap;
36 import java.util.concurrent.Executor;
37 import java.util.concurrent.Executors;
38 import java.util.concurrent.ThreadFactory;
39 import java.util.concurrent.ThreadLocalRandom;
40 import java.util.concurrent.locks.LockSupport;
41 import java.util.function.BooleanSupplier;
42 import jdk.internal.access.JavaLangAccess;
43 import jdk.internal.access.SharedSecrets;
44 import jdk.internal.misc.InnocuousThread;
45 import jdk.internal.misc.TerminatingThreadLocal;
46 import jdk.internal.vm.Continuation;
47 import jdk.internal.vm.ContinuationSupport;
48 import jdk.internal.vm.annotation.Stable;
49
50 /**
51 * I/O poller to allow virtual threads park until a file descriptor is ready for I/O.
52 */
53 public abstract class Poller {
54 private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
55
56 // the poller group for the I/O pollers and poller threads
57 private static final PollerGroup POLLER_GROUP = createPollerGroup();
58
59 // the poller or sub-poller thread (used for observability only)
60 private @Stable Thread owner;
61
62 // maps file descriptors to parked Thread
63 private final Map<Integer, Thread> map = new ConcurrentHashMap<>();
64
65 // shutdown (if supported by poller group)
66 private volatile boolean shutdown;
67
68 /**
69 * Poller mode.
70 */
71 enum Mode {
72 /**
73 * Read and write pollers are platform threads that block waiting for events and
74 * unpark virtual threads when file descriptors are ready for I/O.
75 */
76 SYSTEM_THREADS,
77
78 /**
79 * Read and write pollers are virtual threads that poll for events, yielding
80 * between polls and unparking virtual threads when file descriptors are
81 * ready for I/O. If there are no events then the poller threads park until there
82 * are I/O events to poll. This mode helps to integrate polling with virtual
83 * thread scheduling. The approach is similar to the default scheme in "User-level
84 * Threading: Have Your Cake and Eat It Too" by Karsten and Barghi 2020
85 * (https://dl.acm.org/doi/10.1145/3379483).
86 */
87 VTHREAD_POLLERS,
88
89 /**
90 * Read pollers are per-carrier virtual threads that poll for events, yielding
91 * between polls and unparking virtual threads when file descriptors are ready
92 * for I/O. If there are no events then the poller threads park until there
93 * are I/O events to poll. The write poller is a system-wide platform thread.
94 */
95 POLLER_PER_CARRIER
96 }
97
98 /**
99 * Create and return the PollerGroup.
100 */
101 private static PollerGroup createPollerGroup() {
102 try {
103 PollerProvider provider;
104 if (System.getProperty("jdk.pollerMode") instanceof String s) {
105 Mode mode = switch (s) {
106 case "1" -> Mode.SYSTEM_THREADS;
107 case "2" -> Mode.VTHREAD_POLLERS;
108 case "3" -> Mode.POLLER_PER_CARRIER;
109 default -> {
110 throw new RuntimeException(s + " is not a valid polling mode");
111 }
112 };
113 provider = PollerProvider.createProvider(mode);
114 } else {
115 provider = PollerProvider.createProvider();
116 }
117
118 int readPollers = pollerCount("jdk.readPollers", provider.defaultReadPollers());
119 int writePollers = pollerCount("jdk.writePollers", provider.defaultWritePollers());
120 PollerGroup group = switch (provider.pollerMode()) {
121 case SYSTEM_THREADS -> new SystemThreadsPollerGroup(provider, readPollers, writePollers);
122 case VTHREAD_POLLERS -> new VThreadsPollerGroup(provider, readPollers, writePollers);
123 case POLLER_PER_CARRIER -> new PollerPerCarrierPollerGroup(provider, writePollers);
124 };
125 group.start();
126
127 // Register shutdown hook to initiate an orderly shutdown of the group
128 JLA.registerShutdownHook(2, true, group::shutdown);
129
130 return group;
131 } catch (IOException ioe) {
132 throw new UncheckedIOException(ioe);
133 }
134 }
135
136 /**
137 * Initialize a Poller.
138 */
139 protected Poller() {
140 }
141
142 /**
143 * Closes the poller and release resources. This method can only be used to cleanup
144 * when creating a poller group fails.
145 */
146 abstract void close() throws IOException;
147
148 /**
149 * Sets the poller's thread owner.
150 */
151 private void setOwner() {
152 owner = Thread.currentThread();
153 }
154
155 /**
156 * Returns true if this poller is marked for shutdown.
157 */
158 boolean isShutdown() {
159 return shutdown;
160 }
161
162 /**
163 * Initiates an orderly shutdown of this poller.
164 */
165 void shutdown() {
166 shutdown = true;
167 try { wakeupPoller(); } catch (IOException _) {}
168 }
169
170 /**
171 * Returns the poller's file descriptor to use when polling with the master poller.
172 * @throws UnsupportedOperationException if not supported
173 */
174 int fdVal() {
175 throw new UnsupportedOperationException();
176 }
177
178 /**
179 * Register the file descriptor with the I/O event management facility so that it is
180 * polled when the file descriptor is ready for I/O. The registration is "one shot",
181 * meaning it should be polled at most once.
182 */
183 abstract void implStartPoll(int fdVal) throws IOException;
184
185 /**
186 * Deregister a file descriptor from the I/O event management facility. This may be
187 * a no-op in some implementations when the file descriptor has already been polled.
188 * @param polled true if the file descriptor has already been polled
189 */
190 abstract void implStopPoll(int fdVal, boolean polled) throws IOException;
191
192 /**
193 * Poll for events. The {@link #polled(int)} method is invoked for each
194 * polled file descriptor.
195 *
196 * @param timeout if positive then block for up to {@code timeout} milliseconds,
197 * if zero then don't block, if -1 then block indefinitely
198 * @return >0 if file descriptors are polled, 0 if no file descriptor polled
199 */
200 abstract int poll(int timeout) throws IOException;
201
202 /**
203 * Wakeup the poller thread if blocked in poll so it can shutdown.
204 */
205 abstract void wakeupPoller() throws IOException;
206
207 /**
208 * Callback by the poll method when a file descriptor is polled.
209 */
210 final void polled(int fdVal) {
211 Thread t = map.remove(fdVal);
212 if (t != null) {
213 LockSupport.unpark(t);
214 }
215 }
216
217 /**
218 * Parks the current thread until a file descriptor is ready for the given op.
219 * @param blocker the object that the thread is polling
220 * @param fdVal the file descriptor
221 * @param event POLLIN or POLLOUT
222 * @param nanos the waiting time or 0 to wait indefinitely
223 * @param isOpen supplies a boolean to indicate if the enclosing object is open
224 */
225 public static void poll(Object blocker, int fdVal, int event, long nanos,
226 BooleanSupplier isOpen) throws IOException {
227 POLLER_GROUP.poll(blocker, fdVal, event, nanos, isOpen);
228 }
229
230 /**
231 * Parks the current thread until a Selector's file descriptor is ready.
232 * @param blocker the object that the thread is polling
233 * @param fdVal the Selector's file descriptor
234 * @param nanos the waiting time or 0 to wait indefinitely
235 */
236 public static void pollSelector(Object blocker, int fdVal, long nanos) throws IOException {
237 POLLER_GROUP.pollSelector(blocker, fdVal, nanos);
238 }
239
240 /**
241 * Unpark the given thread so that it stops polling.
242 */
243 public static void stopPoll(Thread thread) {
244 LockSupport.unpark(thread);
245 }
246
247 /**
248 * Parks the current thread until a file descriptor is ready.
249 *
250 * <p> In POLLER_PER_CARRIER mode, does not park if the poller has shut down
251 * because its carrier terminated. This allows the caller to retry with another
252 * poller.
253 *
254 * <p> During VM termination, this method parks if the channel/socket is
255 * open, even if the poller has shut down, to prevent the caller from
256 * spinning as it retries the I/O operation.
257 */
258 private void poll(Object blocker, int fdVal, long nanos,
259 BooleanSupplier isOpen) throws IOException {
260 startPoll(fdVal);
261 try {
262 if (isOpen.getAsBoolean() && (!isShutdown() || POLLER_GROUP.isShutdown())) {
263 if (nanos > 0) {
264 LockSupport.parkNanos(blocker, nanos);
265 } else {
266 LockSupport.park(blocker);
267 }
268 }
269 } finally {
270 stopPoll(fdVal);
271 }
272 }
273
274 /**
275 * Register a file descriptor with the I/O event management facility so that it is
276 * polled when the file descriptor is ready for I/O.
277 */
278 private void startPoll(int fdVal) throws IOException {
279 Thread previous = map.put(fdVal, Thread.currentThread());
280 assert previous == null;
281 try {
282 implStartPoll(fdVal);
283 } catch (Throwable t) {
284 map.remove(fdVal);
285 throw t;
286 } finally {
287 Reference.reachabilityFence(this);
288 }
289 }
290
291 /**
292 * Deregister a file descriptor from the I/O event management facility.
293 */
294 private void stopPoll(int fdVal) throws IOException {
295 Thread previous = map.remove(fdVal);
296 boolean polled = (previous == null);
297 assert polled || previous == Thread.currentThread();
298 try {
299 implStopPoll(fdVal, polled);
300 } finally {
301 Reference.reachabilityFence(this);
302 }
303 }
304
305 /**
306 * Master polling loop. The {@link #polled(int)} method is invoked for each file
307 * descriptor that is polled.
308 */
309 private void pollerLoop() {
310 setOwner();
311 try {
312 while (!isShutdown()) {
313 poll(-1);
314 }
315 } catch (Exception e) {
316 e.printStackTrace();
317 }
318 }
319
320 /**
321 * Sub-poller polling loop. The {@link #polled(int)} method is invoked for each file
322 * descriptor that is polled.
323 *
324 * The sub-poller registers its file descriptor with the master poller to park until
325 * there are events to poll. When unparked, it does non-blocking polls and parks
326 * again when there are no more events. The sub-poller yields after each poll to help
327 * with fairness and to avoid re-registering with the master poller where possible.
328 */
329 private void subPollerLoop(Poller masterPoller) {
330 assert Thread.currentThread().isVirtual();
331 setOwner();
332 try {
333 int polled = 0;
334 while (!isShutdown()) {
335 if (polled == 0) {
336 masterPoller.poll(this, fdVal(), 0, () -> true); // park
337 } else {
338 Thread.yield();
339 }
340 polled = poll(0);
341 }
342 } catch (Exception e) {
343 e.printStackTrace();
344 }
345 }
346
347 /**
348 * Unparks all threads waiting on a file descriptor registered with this poller.
349 */
350 private void wakeupAll() {
351 map.values().forEach(LockSupport::unpark);
352 }
353
354 @Override
355 public String toString() {
356 return String.format("%s [registered = %d, owner = %s]",
357 Objects.toIdentityString(this), map.size(), owner);
358 }
359
360 /**
361 * A group of poller threads that support virtual threads polling file descriptors.
362 */
363 static abstract class PollerGroup {
364 private final PollerProvider provider;
365 private volatile boolean shutdown;
366
367 PollerGroup(PollerProvider provider) {
368 this.provider = provider;
369 }
370
371 final PollerProvider provider() {
372 return provider;
373 }
374
375 /**
376 * Starts the poller group and any system-wide poller threads.
377 */
378 abstract void start();
379
380 /**
381 * Prepares for VM termination by initiating an orderly shutdown of the
382 * system-wide pollers running in platform threads.
383 */
384 abstract void prepareForTermination();
385
386 /**
387 * Marks the poller group as shutdown and prepares for VM termination.
388 */
389 final void shutdown() {
390 shutdown = true;
391 prepareForTermination();
392 }
393
394 /**
395 * Returns true if the poller group has been shutdown (VM termination).
396 */
397 final boolean isShutdown() {
398 return shutdown;
399 }
400
401 /**
402 * Parks the current thread until a file descriptor is ready for the given op.
403 */
404 abstract void poll(Object blocker, int fdVal, int event, long nanos,
405 BooleanSupplier isOpen) throws IOException;
406
407 /**
408 * Parks the current thread until a Selector's file descriptor is ready.
409 */
410 void pollSelector(Object blocker, int fdVal, long nanos) throws IOException {
411 poll(blocker, fdVal, Net.POLLIN, nanos, () -> true);
412 }
413
414 /**
415 * Starts a platform thread to run the given task.
416 */
417 protected final void startPlatformThread(String name, Runnable task) {
418 Thread thread = InnocuousThread.newSystemThread(name, task);
419 thread.setDaemon(true);
420 thread.setUncaughtExceptionHandler((t, e) -> e.printStackTrace());
421 thread.start();
422 }
423
424 /**
425 * Return the master poller, or null if no master poller.
426 */
427 abstract Poller masterPoller();
428
429 /**
430 * Return the read pollers.
431 */
432 abstract List<Poller> readPollers();
433
434 /**
435 * Return the write pollers.
436 */
437 abstract List<Poller> writePollers();
438
439 /**
440 * Close the given pollers.
441 */
442 static void closeAll(Poller... pollers) {
443 for (Poller poller : pollers) {
444 if (poller != null) {
445 try {
446 poller.close();
447 } catch (IOException _) { }
448 }
449 }
450 }
451 }
452
453 /**
454 * SYSTEM_THREADS poller group. The read and write pollers are system-wide platform
455 * threads. To avoid a file descriptor being registered with both a read and write
456 * poller at the same time, the poller group can be configured to run without a
457 * write poller, in which case polling for POLLOUT does timed-parked to force the
458 * caller to retry write ops until they succeed (or fail).
459 */
460 private static class SystemThreadsPollerGroup extends PollerGroup {
461 // system-wide read and write pollers
462 private final Poller[] readPollers;
463 private final Poller[] writePollers;
464
465 SystemThreadsPollerGroup(PollerProvider provider,
466 int readPollerCount,
467 int writePollerCount) throws IOException {
468 super(provider);
469 Poller[] readPollers = new Poller[readPollerCount];
470 Poller[] writePollers = new Poller[writePollerCount];
471 try {
472 for (int i = 0; i < readPollerCount; i++) {
473 readPollers[i] = provider.readPoller(false);
474 }
475 for (int i = 0; i < writePollerCount; i++) {
476 writePollers[i] = provider.writePoller(false);
477 }
478 } catch (Throwable e) {
479 closeAll(readPollers);
480 closeAll(writePollers);
481 throw e;
482 }
483
484 this.readPollers = readPollers;
485 this.writePollers = writePollers;
486 }
487
488 @Override
489 void start() {
490 Arrays.stream(readPollers).forEach(p -> {
491 startPlatformThread("Read-Poller", p::pollerLoop);
492 });
493 Arrays.stream(writePollers).forEach(p -> {
494 startPlatformThread("Write-Poller", p::pollerLoop);
495 });
496 }
497
498 @Override
499 void prepareForTermination() {
500 Arrays.stream(readPollers).forEach(Poller::shutdown);
501 Arrays.stream(writePollers).forEach(Poller::shutdown);
502 }
503
504 private Poller readPoller(int fdVal) {
505 int index = provider().fdValToIndex(fdVal, readPollers.length);
506 return readPollers[index];
507 }
508
509 private Poller writePoller(int fdVal) {
510 if (writePollers.length > 0) {
511 int index = provider().fdValToIndex(fdVal, writePollers.length);
512 return writePollers[index];
513 } else {
514 return null;
515 }
516 }
517
518 @Override
519 void poll(Object blocker, int fdVal, int event, long nanos,
520 BooleanSupplier isOpen) throws IOException {
521 if (event == Net.POLLIN) {
522 readPoller(fdVal).poll(blocker, fdVal, nanos, isOpen);
523 } else {
524 Poller writePoller = writePoller(fdVal);
525 if (writePoller != null) {
526 writePoller.poll(blocker, fdVal, nanos, isOpen);
527 } else {
528 // random delay in [50ms, 120ms)
529 int max = ThreadLocalRandom.current().nextInt(50_000_000, 120_000_000);
530 long delay = (nanos > 0) ? Math.min(nanos, max) : max;
531 LockSupport.parkNanos(blocker, delay);
532 }
533 }
534 }
535
536 @Override
537 Poller masterPoller() {
538 return null;
539 }
540
541 @Override
542 List<Poller> readPollers() {
543 return List.of(readPollers);
544 }
545
546 @Override
547 List<Poller> writePollers() {
548 return List.of(writePollers);
549 }
550 }
551
552 /**
553 * VTHREAD_POLLERS poller group. The read and write pollers are virtual threads.
554 * When read and write pollers need to block then they register with a system-wide
555 * "master poller" that runs in a dedicated platform thread.
556 */
557 private static class VThreadsPollerGroup extends PollerGroup {
558 private final Poller masterPoller;
559 private final Poller[] readPollers;
560 private final Poller[] writePollers;
561
562 // keep virtual thread pollers alive
563 private final Executor executor;
564
565 VThreadsPollerGroup(PollerProvider provider,
566 int readPollerCount,
567 int writePollerCount) throws IOException {
568 super(provider);
569 Poller masterPoller = provider.readPoller(false);
570 Poller[] readPollers = new Poller[readPollerCount];
571 Poller[] writePollers = new Poller[writePollerCount];
572
573 try {
574 for (int i = 0; i < readPollerCount; i++) {
575 readPollers[i] = provider.readPoller(true);
576 }
577 for (int i = 0; i < writePollerCount; i++) {
578 writePollers[i] = provider.writePoller(true);
579 }
580 } catch (Throwable e) {
581 masterPoller.close();
582 closeAll(readPollers);
583 closeAll(writePollers);
584 throw e;
585 }
586
587 this.masterPoller = masterPoller;
588 this.readPollers = readPollers;
589 this.writePollers = writePollers;
590
591 ThreadFactory factory = Thread.ofVirtual()
592 .inheritInheritableThreadLocals(false)
593 .name("SubPoller-", 0)
594 .uncaughtExceptionHandler((_, e) -> e.printStackTrace())
595 .factory();
596 this.executor = Executors.newThreadPerTaskExecutor(factory);
597 }
598
599 @Override
600 void start() {
601 startPlatformThread("Master-Poller", masterPoller::pollerLoop);
602 Arrays.stream(readPollers).forEach(p -> {
603 executor.execute(() -> p.subPollerLoop(masterPoller));
604 });
605 Arrays.stream(writePollers).forEach(p -> {
606 executor.execute(() -> p.subPollerLoop(masterPoller));
607 });
608 }
609
610 @Override
611 void prepareForTermination() {
612 masterPoller.shutdown();
613 }
614
615 private Poller readPoller(int fdVal) {
616 int index = provider().fdValToIndex(fdVal, readPollers.length);
617 return readPollers[index];
618 }
619
620 private Poller writePoller(int fdVal) {
621 int index = provider().fdValToIndex(fdVal, writePollers.length);
622 return writePollers[index];
623 }
624
625 @Override
626 void poll(Object blocker, int fdVal, int event, long nanos,
627 BooleanSupplier isOpen) throws IOException {
628 Poller poller = (event == Net.POLLIN)
629 ? readPoller(fdVal)
630 : writePoller(fdVal);
631 poller.poll(blocker, fdVal, nanos, isOpen);
632 }
633
634 @Override
635 void pollSelector(Object blocker, int fdVal, long nanos) throws IOException {
636 masterPoller.poll(blocker, fdVal, nanos, () -> true);
637 }
638
639 @Override
640 Poller masterPoller() {
641 return masterPoller;
642 }
643
644 @Override
645 List<Poller> readPollers() {
646 return List.of(readPollers);
647 }
648
649 @Override
650 List<Poller> writePollers() {
651 return List.of(writePollers);
652 }
653 }
654
655 /**
656 * POLLER_PER_CARRIER poller group. The read poller is a per-carrier virtual thread.
657 * When a virtual thread polls a file descriptor for POLLIN, then it will use (almost
658 * always, not guaranteed) the read poller for its carrier. When a read poller needs
659 * to block then it registers with a system-wide "master poller" that runs in a
660 * dedicated platform thread. The read poller terminates if the carrier terminates.
661 * The write pollers are system-wide platform threads (usually one).
662 */
663 private static class PollerPerCarrierPollerGroup extends PollerGroup {
664 private record CarrierPoller(PollerPerCarrierPollerGroup group, Poller readPoller) { }
665 private static final TerminatingThreadLocal<CarrierPoller> CARRIER_POLLER =
666 new TerminatingThreadLocal<>() {
667 @Override
668 protected void threadTerminated(CarrierPoller carrierPoller) {
669 Poller readPoller = carrierPoller.readPoller();
670 carrierPoller.group().carrierTerminated(readPoller);
671 }
672 };
673
674 private final Poller masterPoller;
675 private final Set<Poller> readPollers;
676 private final Poller[] writePollers;
677
678 /**
679 * Create a PollerPerCarrierPollerGroup with the given number of write pollers.
680 */
681 PollerPerCarrierPollerGroup(PollerProvider provider,
682 int writePollerCount) throws IOException {
683 super(provider);
684 Poller masterPoller = provider.readPoller(false);
685 Poller[] writePollers = new Poller[writePollerCount];
686 try {
687 for (int i = 0; i < writePollerCount; i++) {
688 writePollers[i] = provider.writePoller(false);
689 }
690 } catch (Throwable e) {
691 masterPoller.close();
692 closeAll(writePollers);
693 throw e;
694 }
695 this.masterPoller = masterPoller;
696 this.readPollers = ConcurrentHashMap.newKeySet();;
697 this.writePollers = writePollers;
698 }
699
700 @Override
701 void start() {
702 startPlatformThread("Master-Poller", masterPoller::pollerLoop);
703 Arrays.stream(writePollers).forEach(p -> {
704 startPlatformThread("Write-Poller", p::pollerLoop);
705 });
706 }
707
708 @Override
709 void prepareForTermination() {
710 Arrays.stream(writePollers).forEach(Poller::shutdown);
711 masterPoller.shutdown();
712 }
713
714 private Poller writePoller(int fdVal) {
715 int index = provider().fdValToIndex(fdVal, writePollers.length);
716 return writePollers[index];
717 }
718
719 /**
720 * Starts a read sub-poller in a virtual thread.
721 */
722 private Poller startReadPoller() throws IOException {
723 assert Thread.currentThread().isVirtual() && ContinuationSupport.isSupported();
724
725 // create read sub-poller
726 Poller readPoller = provider().readPoller(true);
727 readPollers.add(readPoller);
728
729 // start virtual thread to execute sub-polling loop
730 Thread carrier = JLA.currentCarrierThread();
731 Thread.Builder.OfVirtual builder = Thread.ofVirtual()
732 .inheritInheritableThreadLocals(false)
733 .name(carrier.getName() + "-Read-Poller")
734 .uncaughtExceptionHandler((_, e) -> e.printStackTrace());
735 Thread thread = JLA.defaultVirtualThreadScheduler()
736 .newThread(builder, carrier, () -> subPollerLoop(readPoller))
737 .thread();
738 thread.start();
739 return readPoller;
740 }
741
742 /**
743 * Returns the read poller for the current carrier, starting it if required.
744 */
745 private Poller readPoller() throws IOException {
746 assert Thread.currentThread().isVirtual() && ContinuationSupport.isSupported();
747 Continuation.pin();
748 try {
749 CarrierPoller carrierPoller = CARRIER_POLLER.get();
750 if (carrierPoller != null) {
751 return carrierPoller.readPoller();
752 } else {
753 // first poll on this carrier will start poller
754 Poller readPoller = startReadPoller();
755 CARRIER_POLLER.set(new CarrierPoller(this, readPoller));
756 return readPoller;
757 }
758 } finally {
759 Continuation.unpin();
760 }
761 }
762
763 @Override
764 void poll(Object blocker, int fdVal, int event, long nanos,
765 BooleanSupplier isOpen) throws IOException {
766 // for POLLIN, get the read poller for this carrier
767 if (event == Net.POLLIN
768 && Thread.currentThread().isVirtual()
769 && ContinuationSupport.isSupported()) {
770 readPoller().poll(blocker, fdVal, nanos, isOpen);
771 return;
772 }
773
774 // -XX:-VMContinuations or POLLIN from platform thread does master poller
775 if (event == Net.POLLIN) {
776 masterPoller.poll(blocker, fdVal, nanos, isOpen);
777 } else {
778 writePoller(fdVal).poll(blocker, fdVal, nanos, isOpen);
779 }
780 }
781
782 @Override
783 void pollSelector(Object blocker, int fdVal, long nanos) throws IOException {
784 masterPoller.poll(blocker, fdVal, nanos, () -> true);
785 }
786
787 /**
788 * Sub-poller polling loop.
789 */
790 private void subPollerLoop(Poller readPoller) {
791 try {
792 readPoller.subPollerLoop(masterPoller);
793 } finally {
794 // wakeup all threads waiting on file descriptors registered with the
795 // read poller, these I/O operation will migrate to another carrier.
796 readPoller.wakeupAll();
797
798 // remove from serviceability view
799 readPollers.remove(readPoller);
800 }
801 }
802
803 /**
804 * Invoked by the carrier thread before it terminates.
805 */
806 private void carrierTerminated(Poller readPoller) {
807 readPoller.shutdown();
808 }
809
810 @Override
811 Poller masterPoller() {
812 return masterPoller;
813 }
814
815 @Override
816 List<Poller> readPollers() {
817 return readPollers.stream().toList();
818 }
819
820 @Override
821 List<Poller> writePollers() {
822 return List.of(writePollers);
823 }
824 }
825
826 /**
827 * Reads the given property name to get the poller count. If the property is
828 * set then the value must be a power of 2. Returns 1 if the property is not
829 * set.
830 * @throws IllegalArgumentException if the property is set to a value that
831 * is not a power of 2.
832 */
833 private static int pollerCount(String propName, int defaultCount) {
834 String s = System.getProperty(propName);
835 int count = (s != null) ? Integer.parseInt(s) : defaultCount;
836
837 // check power of 2
838 if (count != Integer.highestOneBit(count)) {
839 String msg = propName + " is set to a value that is not a power of 2";
840 throw new IllegalArgumentException(msg);
841 }
842 return count;
843 }
844
845 /**
846 * Return the master poller or null if there is no master poller.
847 */
848 public static Poller masterPoller() {
849 return POLLER_GROUP.masterPoller();
850 }
851
852 /**
853 * Return the list of read pollers.
854 */
855 public static List<Poller> readPollers() {
856 return POLLER_GROUP.readPollers();
857 }
858
859 /**
860 * Return the list of write pollers.
861 */
862 public static List<Poller> writePollers() {
863 return POLLER_GROUP.writePollers();
864 }
865 }