1 /* 2 * Copyright (c) 2018, 2025, 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 java.lang; 26 27 import java.util.Locale; 28 import java.util.Objects; 29 import java.util.concurrent.CountDownLatch; 30 import java.util.concurrent.Executor; 31 import java.util.concurrent.Executors; 32 import java.util.concurrent.ForkJoinPool; 33 import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory; 34 import java.util.concurrent.ForkJoinTask; 35 import java.util.concurrent.Future; 36 import java.util.concurrent.RejectedExecutionException; 37 import java.util.concurrent.ScheduledExecutorService; 38 import java.util.concurrent.ScheduledThreadPoolExecutor; 39 import java.util.concurrent.TimeUnit; 40 import jdk.internal.event.VirtualThreadEndEvent; 41 import jdk.internal.event.VirtualThreadStartEvent; 42 import jdk.internal.event.VirtualThreadSubmitFailedEvent; 43 import jdk.internal.misc.CarrierThread; 44 import jdk.internal.misc.InnocuousThread; 45 import jdk.internal.misc.Unsafe; 46 import jdk.internal.vm.Continuation; 47 import jdk.internal.vm.ContinuationScope; 48 import jdk.internal.vm.StackableScope; 49 import jdk.internal.vm.ThreadContainer; 50 import jdk.internal.vm.ThreadContainers; 51 import jdk.internal.vm.annotation.ChangesCurrentThread; 52 import jdk.internal.vm.annotation.Hidden; 53 import jdk.internal.vm.annotation.IntrinsicCandidate; 54 import jdk.internal.vm.annotation.JvmtiHideEvents; 55 import jdk.internal.vm.annotation.JvmtiMountTransition; 56 import jdk.internal.vm.annotation.ReservedStackAccess; 57 import sun.nio.ch.Interruptible; 58 import static java.util.concurrent.TimeUnit.*; 59 60 /** 61 * A thread that is scheduled by the Java virtual machine rather than the operating system. 62 */ 63 final class VirtualThread extends BaseVirtualThread { 64 private static final Unsafe U = Unsafe.getUnsafe(); 65 private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads"); 66 private static final ForkJoinPool DEFAULT_SCHEDULER = createDefaultScheduler(); 67 68 private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state"); 69 private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit"); 70 private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread"); 71 private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination"); 72 private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList"); 73 74 // scheduler and continuation 75 private final Executor scheduler; 76 private final Continuation cont; 77 private final Runnable runContinuation; 78 79 // virtual thread state, accessed by VM 80 private volatile int state; 81 82 /* 83 * Virtual thread state transitions: 84 * 85 * NEW -> STARTED // Thread.start, schedule to run 86 * STARTED -> TERMINATED // failed to start 87 * STARTED -> RUNNING // first run 88 * RUNNING -> TERMINATED // done 89 * 90 * RUNNING -> PARKING // Thread parking with LockSupport.park 91 * PARKING -> PARKED // cont.yield successful, parked indefinitely 92 * PARKING -> PINNED // cont.yield failed, parked indefinitely on carrier 93 * PARKED -> UNPARKED // unparked, may be scheduled to continue 94 * PINNED -> RUNNING // unparked, continue execution on same carrier 95 * UNPARKED -> RUNNING // continue execution after park 96 * 97 * RUNNING -> TIMED_PARKING // Thread parking with LockSupport.parkNanos 98 * TIMED_PARKING -> TIMED_PARKED // cont.yield successful, timed-parked 99 * TIMED_PARKING -> TIMED_PINNED // cont.yield failed, timed-parked on carrier 100 * TIMED_PARKED -> UNPARKED // unparked, may be scheduled to continue 101 * TIMED_PINNED -> RUNNING // unparked, continue execution on same carrier 102 * 103 * RUNNING -> BLOCKING // blocking on monitor enter 104 * BLOCKING -> BLOCKED // blocked on monitor enter 105 * BLOCKED -> UNBLOCKED // unblocked, may be scheduled to continue 106 * UNBLOCKED -> RUNNING // continue execution after blocked on monitor enter 107 * 108 * RUNNING -> WAITING // transitional state during wait on monitor 109 * WAITING -> WAIT // waiting on monitor 110 * WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner 111 * WAIT -> UNBLOCKED // timed-out/interrupted 112 * 113 * RUNNING -> TIMED_WAITING // transition state during timed-waiting on monitor 114 * TIMED_WAITING -> TIMED_WAIT // timed-waiting on monitor 115 * TIMED_WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner 116 * TIMED_WAIT -> UNBLOCKED // timed-out/interrupted 117 * 118 * RUNNING -> YIELDING // Thread.yield 119 * YIELDING -> YIELDED // cont.yield successful, may be scheduled to continue 120 * YIELDING -> RUNNING // cont.yield failed 121 * YIELDED -> RUNNING // continue execution after Thread.yield 122 */ 123 private static final int NEW = 0; 124 private static final int STARTED = 1; 125 private static final int RUNNING = 2; // runnable-mounted 126 127 // untimed and timed parking 128 private static final int PARKING = 3; 129 private static final int PARKED = 4; // unmounted 130 private static final int PINNED = 5; // mounted 131 private static final int TIMED_PARKING = 6; 132 private static final int TIMED_PARKED = 7; // unmounted 133 private static final int TIMED_PINNED = 8; // mounted 134 private static final int UNPARKED = 9; // unmounted but runnable 135 136 // Thread.yield 137 private static final int YIELDING = 10; 138 private static final int YIELDED = 11; // unmounted but runnable 139 140 // monitor enter 141 private static final int BLOCKING = 12; 142 private static final int BLOCKED = 13; // unmounted 143 private static final int UNBLOCKED = 14; // unmounted but runnable 144 145 // monitor wait/timed-wait 146 private static final int WAITING = 15; 147 private static final int WAIT = 16; // waiting in Object.wait 148 private static final int TIMED_WAITING = 17; 149 private static final int TIMED_WAIT = 18; // waiting in timed-Object.wait 150 151 private static final int TERMINATED = 99; // final state 152 153 // can be suspended from scheduling when unmounted 154 private static final int SUSPENDED = 1 << 8; 155 156 // parking permit made available by LockSupport.unpark 157 private volatile boolean parkPermit; 158 159 // blocking permit made available by unblocker thread when another thread exits monitor 160 private volatile boolean blockPermit; 161 162 // true when on the list of virtual threads waiting to be unblocked 163 private volatile boolean onWaitingList; 164 165 // next virtual thread on the list of virtual threads waiting to be unblocked 166 private volatile VirtualThread next; 167 168 // notified by Object.notify/notifyAll while waiting in Object.wait 169 private volatile boolean notified; 170 171 // true when waiting in Object.wait, false for VM internal uninterruptible Object.wait 172 private volatile boolean interruptibleWait; 173 174 // timed-wait support 175 private byte timedWaitSeqNo; 176 177 // timeout for timed-park and timed-wait, only accessed on current/carrier thread 178 private long timeout; 179 180 // timer task for timed-park and timed-wait, only accessed on current/carrier thread 181 private Future<?> timeoutTask; 182 183 // carrier thread when mounted, accessed by VM 184 private volatile Thread carrierThread; 185 186 // termination object when joining, created lazily if needed 187 private volatile CountDownLatch termination; 188 189 /** 190 * Returns the default scheduler. 191 */ 192 static Executor defaultScheduler() { 193 return DEFAULT_SCHEDULER; 194 } 195 196 /** 197 * Returns the continuation scope used for virtual threads. 198 */ 199 static ContinuationScope continuationScope() { 200 return VTHREAD_SCOPE; 201 } 202 203 /** 204 * Creates a new {@code VirtualThread} to run the given task with the given 205 * scheduler. If the given scheduler is {@code null} and the current thread 206 * is a platform thread then the newly created virtual thread will use the 207 * default scheduler. If given scheduler is {@code null} and the current 208 * thread is a virtual thread then the current thread's scheduler is used. 209 * 210 * @param scheduler the scheduler or null 211 * @param name thread name 212 * @param characteristics characteristics 213 * @param task the task to execute 214 */ 215 VirtualThread(Executor scheduler, String name, int characteristics, Runnable task) { 216 super(name, characteristics, /*bound*/ false); 217 Objects.requireNonNull(task); 218 219 // choose scheduler if not specified 220 if (scheduler == null) { 221 Thread parent = Thread.currentThread(); 222 if (parent instanceof VirtualThread vparent) { 223 scheduler = vparent.scheduler; 224 } else { 225 scheduler = DEFAULT_SCHEDULER; 226 } 227 } 228 229 this.scheduler = scheduler; 230 this.cont = new VThreadContinuation(this, task); 231 this.runContinuation = this::runContinuation; 232 } 233 234 /** 235 * The continuation that a virtual thread executes. 236 */ 237 private static class VThreadContinuation extends Continuation { 238 VThreadContinuation(VirtualThread vthread, Runnable task) { 239 super(VTHREAD_SCOPE, wrap(vthread, task)); 240 } 241 @Override 242 protected void onPinned(Continuation.Pinned reason) { 243 } 244 private static Runnable wrap(VirtualThread vthread, Runnable task) { 245 return new Runnable() { 246 @Hidden 247 @JvmtiHideEvents 248 public void run() { 249 vthread.notifyJvmtiStart(); // notify JVMTI 250 try { 251 vthread.run(task); 252 } finally { 253 vthread.notifyJvmtiEnd(); // notify JVMTI 254 } 255 } 256 }; 257 } 258 } 259 260 /** 261 * Runs or continues execution on the current thread. The virtual thread is mounted 262 * on the current thread before the task runs or continues. It unmounts when the 263 * task completes or yields. 264 */ 265 @ChangesCurrentThread // allow mount/unmount to be inlined 266 private void runContinuation() { 267 // the carrier must be a platform thread 268 if (Thread.currentThread().isVirtual()) { 269 throw new WrongThreadException(); 270 } 271 272 // set state to RUNNING 273 int initialState = state(); 274 if (initialState == STARTED || initialState == UNPARKED 275 || initialState == UNBLOCKED || initialState == YIELDED) { 276 // newly started or continue after parking/blocking/Thread.yield 277 if (!compareAndSetState(initialState, RUNNING)) { 278 return; 279 } 280 // consume permit when continuing after parking or blocking. If continue 281 // after a timed-park or timed-wait then the timeout task is cancelled. 282 if (initialState == UNPARKED) { 283 cancelTimeoutTask(); 284 setParkPermit(false); 285 } else if (initialState == UNBLOCKED) { 286 cancelTimeoutTask(); 287 blockPermit = false; 288 } 289 } else { 290 // not runnable 291 return; 292 } 293 294 mount(); 295 try { 296 cont.run(); 297 } finally { 298 unmount(); 299 if (cont.isDone()) { 300 afterDone(); 301 } else { 302 afterYield(); 303 } 304 } 305 } 306 307 /** 308 * Cancel timeout task when continuing after timed-park or timed-wait. 309 * The timeout task may be executing, or may have already completed. 310 */ 311 private void cancelTimeoutTask() { 312 if (timeoutTask != null) { 313 timeoutTask.cancel(false); 314 timeoutTask = null; 315 } 316 } 317 318 /** 319 * Submits the runContinuation task to the scheduler. For the default scheduler, 320 * and calling it on a worker thread, the task will be pushed to the local queue, 321 * otherwise it will be pushed to an external submission queue. 322 * @param scheduler the scheduler 323 * @param retryOnOOME true to retry indefinitely if OutOfMemoryError is thrown 324 * @throws RejectedExecutionException 325 */ 326 private void submitRunContinuation(Executor scheduler, boolean retryOnOOME) { 327 boolean done = false; 328 while (!done) { 329 try { 330 // Pin the continuation to prevent the virtual thread from unmounting 331 // when submitting a task. For the default scheduler this ensures that 332 // the carrier doesn't change when pushing a task. For other schedulers 333 // it avoids deadlock that could arise due to carriers and virtual 334 // threads contending for a lock. 335 if (currentThread().isVirtual()) { 336 Continuation.pin(); 337 try { 338 scheduler.execute(runContinuation); 339 } finally { 340 Continuation.unpin(); 341 } 342 } else { 343 scheduler.execute(runContinuation); 344 } 345 done = true; 346 } catch (RejectedExecutionException ree) { 347 submitFailed(ree); 348 throw ree; 349 } catch (OutOfMemoryError e) { 350 if (retryOnOOME) { 351 U.park(false, 100_000_000); // 100ms 352 } else { 353 throw e; 354 } 355 } 356 } 357 } 358 359 /** 360 * Submits the runContinuation task to the given scheduler as an external submit. 361 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds. 362 * @throws RejectedExecutionException 363 * @see ForkJoinPool#externalSubmit(ForkJoinTask) 364 */ 365 private void externalSubmitRunContinuation(ForkJoinPool pool) { 366 assert Thread.currentThread() instanceof CarrierThread; 367 try { 368 pool.externalSubmit(ForkJoinTask.adapt(runContinuation)); 369 } catch (RejectedExecutionException ree) { 370 submitFailed(ree); 371 throw ree; 372 } catch (OutOfMemoryError e) { 373 submitRunContinuation(pool, true); 374 } 375 } 376 377 /** 378 * Submits the runContinuation task to the scheduler. For the default scheduler, 379 * and calling it on a worker thread, the task will be pushed to the local queue, 380 * otherwise it will be pushed to an external submission queue. 381 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds. 382 * @throws RejectedExecutionException 383 */ 384 private void submitRunContinuation() { 385 submitRunContinuation(scheduler, true); 386 } 387 388 /** 389 * Lazy submit the runContinuation task if invoked on a carrier thread and its local 390 * queue is empty. If not empty, or invoked by another thread, then this method works 391 * like submitRunContinuation and just submits the task to the scheduler. 392 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds. 393 * @throws RejectedExecutionException 394 * @see ForkJoinPool#lazySubmit(ForkJoinTask) 395 */ 396 private void lazySubmitRunContinuation() { 397 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) { 398 ForkJoinPool pool = ct.getPool(); 399 try { 400 pool.lazySubmit(ForkJoinTask.adapt(runContinuation)); 401 } catch (RejectedExecutionException ree) { 402 submitFailed(ree); 403 throw ree; 404 } catch (OutOfMemoryError e) { 405 submitRunContinuation(); 406 } 407 } else { 408 submitRunContinuation(); 409 } 410 } 411 412 /** 413 * Submits the runContinuation task to the scheduler. For the default scheduler, and 414 * calling it a virtual thread that uses the default scheduler, the task will be 415 * pushed to an external submission queue. This method may throw OutOfMemoryError. 416 * @throws RejectedExecutionException 417 * @throws OutOfMemoryError 418 */ 419 private void externalSubmitRunContinuationOrThrow() { 420 if (scheduler == DEFAULT_SCHEDULER && currentCarrierThread() instanceof CarrierThread ct) { 421 try { 422 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation)); 423 } catch (RejectedExecutionException ree) { 424 submitFailed(ree); 425 throw ree; 426 } 427 } else { 428 submitRunContinuation(scheduler, false); 429 } 430 } 431 432 /** 433 * If enabled, emits a JFR VirtualThreadSubmitFailedEvent. 434 */ 435 private void submitFailed(RejectedExecutionException ree) { 436 var event = new VirtualThreadSubmitFailedEvent(); 437 if (event.isEnabled()) { 438 event.javaThreadId = threadId(); 439 event.exceptionMessage = ree.getMessage(); 440 event.commit(); 441 } 442 } 443 444 /** 445 * Runs a task in the context of this virtual thread. 446 */ 447 private void run(Runnable task) { 448 assert Thread.currentThread() == this && state == RUNNING; 449 450 // emit JFR event if enabled 451 if (VirtualThreadStartEvent.isTurnedOn()) { 452 var event = new VirtualThreadStartEvent(); 453 event.javaThreadId = threadId(); 454 event.commit(); 455 } 456 457 Object bindings = Thread.scopedValueBindings(); 458 try { 459 runWith(bindings, task); 460 } catch (Throwable exc) { 461 dispatchUncaughtException(exc); 462 } finally { 463 // pop any remaining scopes from the stack, this may block 464 StackableScope.popAll(); 465 466 // emit JFR event if enabled 467 if (VirtualThreadEndEvent.isTurnedOn()) { 468 var event = new VirtualThreadEndEvent(); 469 event.javaThreadId = threadId(); 470 event.commit(); 471 } 472 } 473 } 474 475 /** 476 * Mounts this virtual thread onto the current platform thread. On 477 * return, the current thread is the virtual thread. 478 */ 479 @ChangesCurrentThread 480 @ReservedStackAccess 481 private void mount() { 482 // notify JVMTI before mount 483 notifyJvmtiMount(/*hide*/true); 484 485 // sets the carrier thread 486 Thread carrier = Thread.currentCarrierThread(); 487 setCarrierThread(carrier); 488 489 // sync up carrier thread interrupted status if needed 490 if (interrupted) { 491 carrier.setInterrupt(); 492 } else if (carrier.isInterrupted()) { 493 synchronized (interruptLock) { 494 // need to recheck interrupted status 495 if (!interrupted) { 496 carrier.clearInterrupt(); 497 } 498 } 499 } 500 501 // set Thread.currentThread() to return this virtual thread 502 carrier.setCurrentThread(this); 503 } 504 505 /** 506 * Unmounts this virtual thread from the carrier. On return, the 507 * current thread is the current platform thread. 508 */ 509 @ChangesCurrentThread 510 @ReservedStackAccess 511 private void unmount() { 512 assert !Thread.holdsLock(interruptLock); 513 514 // set Thread.currentThread() to return the platform thread 515 Thread carrier = this.carrierThread; 516 carrier.setCurrentThread(carrier); 517 518 // break connection to carrier thread, synchronized with interrupt 519 synchronized (interruptLock) { 520 setCarrierThread(null); 521 } 522 carrier.clearInterrupt(); 523 524 // notify JVMTI after unmount 525 notifyJvmtiUnmount(/*hide*/false); 526 } 527 528 /** 529 * Invokes Continuation.yield, notifying JVMTI (if enabled) to hide frames until 530 * the continuation continues. 531 */ 532 @Hidden 533 private boolean yieldContinuation() { 534 notifyJvmtiUnmount(/*hide*/true); 535 try { 536 return Continuation.yield(VTHREAD_SCOPE); 537 } finally { 538 notifyJvmtiMount(/*hide*/false); 539 } 540 } 541 542 /** 543 * Invoked in the context of the carrier thread after the Continuation yields when 544 * parking, blocking on monitor enter, Object.wait, or Thread.yield. 545 */ 546 private void afterYield() { 547 assert carrierThread == null; 548 549 // re-adjust parallelism if the virtual thread yielded when compensating 550 if (currentThread() instanceof CarrierThread ct) { 551 ct.endBlocking(); 552 } 553 554 int s = state(); 555 556 // LockSupport.park/parkNanos 557 if (s == PARKING || s == TIMED_PARKING) { 558 int newState; 559 if (s == PARKING) { 560 setState(newState = PARKED); 561 } else { 562 // schedule unpark 563 long timeout = this.timeout; 564 assert timeout > 0; 565 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS); 566 setState(newState = TIMED_PARKED); 567 } 568 569 // may have been unparked while parking 570 if (parkPermit && compareAndSetState(newState, UNPARKED)) { 571 // lazy submit if local queue is empty 572 lazySubmitRunContinuation(); 573 } 574 return; 575 } 576 577 // Thread.yield 578 if (s == YIELDING) { 579 setState(YIELDED); 580 581 // external submit if there are no tasks in the local task queue 582 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) { 583 externalSubmitRunContinuation(ct.getPool()); 584 } else { 585 submitRunContinuation(); 586 } 587 return; 588 } 589 590 // blocking on monitorenter 591 if (s == BLOCKING) { 592 setState(BLOCKED); 593 594 // may have been unblocked while blocking 595 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) { 596 // lazy submit if local queue is empty 597 lazySubmitRunContinuation(); 598 } 599 return; 600 } 601 602 // Object.wait 603 if (s == WAITING || s == TIMED_WAITING) { 604 int newState; 605 boolean interruptible = interruptibleWait; 606 if (s == WAITING) { 607 setState(newState = WAIT); 608 } else { 609 // For timed-wait, a timeout task is scheduled to execute. The timeout 610 // task will change the thread state to UNBLOCKED and submit the thread 611 // to the scheduler. A sequence number is used to ensure that the timeout 612 // task only unblocks the thread for this timed-wait. We synchronize with 613 // the timeout task to coordinate access to the sequence number and to 614 // ensure the timeout task doesn't execute until the thread has got to 615 // the TIMED_WAIT state. 616 long timeout = this.timeout; 617 assert timeout > 0; 618 synchronized (timedWaitLock()) { 619 byte seqNo = ++timedWaitSeqNo; 620 timeoutTask = schedule(() -> waitTimeoutExpired(seqNo), timeout, MILLISECONDS); 621 setState(newState = TIMED_WAIT); 622 } 623 } 624 625 // may have been notified while in transition to wait state 626 if (notified && compareAndSetState(newState, BLOCKED)) { 627 // may have even been unblocked already 628 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) { 629 submitRunContinuation(); 630 } 631 return; 632 } 633 634 // may have been interrupted while in transition to wait state 635 if (interruptible && interrupted && compareAndSetState(newState, UNBLOCKED)) { 636 submitRunContinuation(); 637 return; 638 } 639 return; 640 } 641 642 assert false; 643 } 644 645 /** 646 * Invoked after the continuation completes. 647 */ 648 private void afterDone() { 649 afterDone(true); 650 } 651 652 /** 653 * Invoked after the continuation completes (or start failed). Sets the thread 654 * state to TERMINATED and notifies anyone waiting for the thread to terminate. 655 * 656 * @param notifyContainer true if its container should be notified 657 */ 658 private void afterDone(boolean notifyContainer) { 659 assert carrierThread == null; 660 setState(TERMINATED); 661 662 // notify anyone waiting for this virtual thread to terminate 663 CountDownLatch termination = this.termination; 664 if (termination != null) { 665 assert termination.getCount() == 1; 666 termination.countDown(); 667 } 668 669 // notify container 670 if (notifyContainer) { 671 threadContainer().remove(this); 672 } 673 674 // clear references to thread locals 675 clearReferences(); 676 } 677 678 /** 679 * Schedules this {@code VirtualThread} to execute. 680 * 681 * @throws IllegalStateException if the container is shutdown or closed 682 * @throws IllegalThreadStateException if the thread has already been started 683 * @throws RejectedExecutionException if the scheduler cannot accept a task 684 */ 685 @Override 686 void start(ThreadContainer container) { 687 if (!compareAndSetState(NEW, STARTED)) { 688 throw new IllegalThreadStateException("Already started"); 689 } 690 691 // bind thread to container 692 assert threadContainer() == null; 693 setThreadContainer(container); 694 695 // start thread 696 boolean addedToContainer = false; 697 boolean started = false; 698 try { 699 container.add(this); // may throw 700 addedToContainer = true; 701 702 // scoped values may be inherited 703 inheritScopedValueBindings(container); 704 705 // submit task to run thread, using externalSubmit if possible 706 externalSubmitRunContinuationOrThrow(); 707 started = true; 708 } finally { 709 if (!started) { 710 afterDone(addedToContainer); 711 } 712 } 713 } 714 715 @Override 716 public void start() { 717 start(ThreadContainers.root()); 718 } 719 720 @Override 721 public void run() { 722 // do nothing 723 } 724 725 /** 726 * Parks until unparked or interrupted. If already unparked then the parking 727 * permit is consumed and this method completes immediately (meaning it doesn't 728 * yield). It also completes immediately if the interrupted status is set. 729 */ 730 @Override 731 void park() { 732 assert Thread.currentThread() == this; 733 734 // complete immediately if parking permit available or interrupted 735 if (getAndSetParkPermit(false) || interrupted) 736 return; 737 738 // park the thread 739 boolean yielded = false; 740 setState(PARKING); 741 try { 742 yielded = yieldContinuation(); 743 } catch (OutOfMemoryError e) { 744 // park on carrier 745 } finally { 746 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING)); 747 if (!yielded) { 748 assert state() == PARKING; 749 setState(RUNNING); 750 } 751 } 752 753 // park on the carrier thread when pinned 754 if (!yielded) { 755 parkOnCarrierThread(false, 0); 756 } 757 } 758 759 /** 760 * Parks up to the given waiting time or until unparked or interrupted. 761 * If already unparked then the parking permit is consumed and this method 762 * completes immediately (meaning it doesn't yield). It also completes immediately 763 * if the interrupted status is set or the waiting time is {@code <= 0}. 764 * 765 * @param nanos the maximum number of nanoseconds to wait. 766 */ 767 @Override 768 void parkNanos(long nanos) { 769 assert Thread.currentThread() == this; 770 771 // complete immediately if parking permit available or interrupted 772 if (getAndSetParkPermit(false) || interrupted) 773 return; 774 775 // park the thread for the waiting time 776 if (nanos > 0) { 777 long startTime = System.nanoTime(); 778 779 // park the thread, afterYield will schedule the thread to unpark 780 boolean yielded = false; 781 timeout = nanos; 782 setState(TIMED_PARKING); 783 try { 784 yielded = yieldContinuation(); 785 } catch (OutOfMemoryError e) { 786 // park on carrier 787 } finally { 788 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING)); 789 if (!yielded) { 790 assert state() == TIMED_PARKING; 791 setState(RUNNING); 792 } 793 } 794 795 // park on carrier thread for remaining time when pinned (or OOME) 796 if (!yielded) { 797 long remainingNanos = nanos - (System.nanoTime() - startTime); 798 parkOnCarrierThread(true, remainingNanos); 799 } 800 } 801 } 802 803 /** 804 * Parks the current carrier thread up to the given waiting time or until 805 * unparked or interrupted. If the virtual thread is interrupted then the 806 * interrupted status will be propagated to the carrier thread. 807 * @param timed true for a timed park, false for untimed 808 * @param nanos the waiting time in nanoseconds 809 */ 810 private void parkOnCarrierThread(boolean timed, long nanos) { 811 assert state() == RUNNING; 812 813 setState(timed ? TIMED_PINNED : PINNED); 814 try { 815 if (!parkPermit) { 816 if (!timed) { 817 U.park(false, 0); 818 } else if (nanos > 0) { 819 U.park(false, nanos); 820 } 821 } 822 } finally { 823 setState(RUNNING); 824 } 825 826 // consume parking permit 827 setParkPermit(false); 828 829 // JFR jdk.VirtualThreadPinned event 830 postPinnedEvent("LockSupport.park"); 831 } 832 833 /** 834 * Call into VM when pinned to record a JFR jdk.VirtualThreadPinned event. 835 * Recording the event in the VM avoids having JFR event recorded in Java 836 * with the same name, but different ID, to events recorded by the VM. 837 */ 838 @Hidden 839 private static native void postPinnedEvent(String op); 840 841 /** 842 * Re-enables this virtual thread for scheduling. If this virtual thread is parked 843 * then its task is scheduled to continue, otherwise its next call to {@code park} or 844 * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block. 845 * @throws RejectedExecutionException if the scheduler cannot accept a task 846 */ 847 @Override 848 void unpark() { 849 if (!getAndSetParkPermit(true) && currentThread() != this) { 850 int s = state(); 851 852 // unparked while parked 853 if ((s == PARKED || s == TIMED_PARKED) && compareAndSetState(s, UNPARKED)) { 854 submitRunContinuation(); 855 return; 856 } 857 858 // unparked while parked when pinned 859 if (s == PINNED || s == TIMED_PINNED) { 860 // unpark carrier thread when pinned 861 disableSuspendAndPreempt(); 862 try { 863 synchronized (carrierThreadAccessLock()) { 864 Thread carrier = carrierThread; 865 if (carrier != null && ((s = state()) == PINNED || s == TIMED_PINNED)) { 866 U.unpark(carrier); 867 } 868 } 869 } finally { 870 enableSuspendAndPreempt(); 871 } 872 return; 873 } 874 } 875 } 876 877 /** 878 * Invoked by unblocker thread to unblock this virtual thread. 879 */ 880 private void unblock() { 881 assert !Thread.currentThread().isVirtual(); 882 blockPermit = true; 883 if (state() == BLOCKED && compareAndSetState(BLOCKED, UNBLOCKED)) { 884 submitRunContinuation(); 885 } 886 } 887 888 /** 889 * Invoked by FJP worker thread or STPE thread when park timeout expires. 890 */ 891 private void parkTimeoutExpired() { 892 assert !VirtualThread.currentThread().isVirtual(); 893 if (!getAndSetParkPermit(true) 894 && (state() == TIMED_PARKED) 895 && compareAndSetState(TIMED_PARKED, UNPARKED)) { 896 lazySubmitRunContinuation(); 897 } 898 } 899 900 /** 901 * Invoked by FJP worker thread or STPE thread when wait timeout expires. 902 * If the virtual thread is in timed-wait then this method will unblock the thread 903 * and submit its task so that it continues and attempts to reenter the monitor. 904 * This method does nothing if the thread has been woken by notify or interrupt. 905 */ 906 private void waitTimeoutExpired(byte seqNo) { 907 assert !Thread.currentThread().isVirtual(); 908 for (;;) { 909 boolean unblocked = false; 910 synchronized (timedWaitLock()) { 911 if (seqNo != timedWaitSeqNo) { 912 // this timeout task is for a past timed-wait 913 return; 914 } 915 int s = state(); 916 if (s == TIMED_WAIT) { 917 unblocked = compareAndSetState(TIMED_WAIT, UNBLOCKED); 918 } else if (s != (TIMED_WAIT | SUSPENDED)) { 919 // notified or interrupted, no longer waiting 920 return; 921 } 922 } 923 if (unblocked) { 924 lazySubmitRunContinuation(); 925 return; 926 } 927 // need to retry when thread is suspended in time-wait 928 Thread.yield(); 929 } 930 } 931 932 /** 933 * Attempts to yield the current virtual thread (Thread.yield). 934 */ 935 void tryYield() { 936 assert Thread.currentThread() == this; 937 setState(YIELDING); 938 boolean yielded = false; 939 try { 940 yielded = yieldContinuation(); // may throw 941 } finally { 942 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING)); 943 if (!yielded) { 944 assert state() == YIELDING; 945 setState(RUNNING); 946 } 947 } 948 } 949 950 /** 951 * Sleep the current thread for the given sleep time (in nanoseconds). If 952 * nanos is 0 then the thread will attempt to yield. 953 * 954 * @implNote This implementation parks the thread for the given sleeping time 955 * and will therefore be observed in PARKED state during the sleep. Parking 956 * will consume the parking permit so this method makes available the parking 957 * permit after the sleep. This may be observed as a spurious, but benign, 958 * wakeup when the thread subsequently attempts to park. 959 * 960 * @param nanos the maximum number of nanoseconds to sleep 961 * @throws InterruptedException if interrupted while sleeping 962 */ 963 void sleepNanos(long nanos) throws InterruptedException { 964 assert Thread.currentThread() == this && nanos >= 0; 965 if (getAndClearInterrupt()) 966 throw new InterruptedException(); 967 if (nanos == 0) { 968 tryYield(); 969 } else { 970 // park for the sleep time 971 try { 972 long remainingNanos = nanos; 973 long startNanos = System.nanoTime(); 974 while (remainingNanos > 0) { 975 parkNanos(remainingNanos); 976 if (getAndClearInterrupt()) { 977 throw new InterruptedException(); 978 } 979 remainingNanos = nanos - (System.nanoTime() - startNanos); 980 } 981 } finally { 982 // may have been unparked while sleeping 983 setParkPermit(true); 984 } 985 } 986 } 987 988 /** 989 * Waits up to {@code nanos} nanoseconds for this virtual thread to terminate. 990 * A timeout of {@code 0} means to wait forever. 991 * 992 * @throws InterruptedException if interrupted while waiting 993 * @return true if the thread has terminated 994 */ 995 boolean joinNanos(long nanos) throws InterruptedException { 996 if (state() == TERMINATED) 997 return true; 998 999 // ensure termination object exists, then re-check state 1000 CountDownLatch termination = getTermination(); 1001 if (state() == TERMINATED) 1002 return true; 1003 1004 // wait for virtual thread to terminate 1005 if (nanos == 0) { 1006 termination.await(); 1007 } else { 1008 boolean terminated = termination.await(nanos, NANOSECONDS); 1009 if (!terminated) { 1010 // waiting time elapsed 1011 return false; 1012 } 1013 } 1014 assert state() == TERMINATED; 1015 return true; 1016 } 1017 1018 @Override 1019 void blockedOn(Interruptible b) { 1020 disableSuspendAndPreempt(); 1021 try { 1022 super.blockedOn(b); 1023 } finally { 1024 enableSuspendAndPreempt(); 1025 } 1026 } 1027 1028 @Override 1029 public void interrupt() { 1030 if (Thread.currentThread() != this) { 1031 // if current thread is a virtual thread then prevent it from being 1032 // suspended or unmounted when entering or holding interruptLock 1033 Interruptible blocker; 1034 disableSuspendAndPreempt(); 1035 try { 1036 synchronized (interruptLock) { 1037 interrupted = true; 1038 blocker = nioBlocker(); 1039 if (blocker != null) { 1040 blocker.interrupt(this); 1041 } 1042 1043 // interrupt carrier thread if mounted 1044 Thread carrier = carrierThread; 1045 if (carrier != null) carrier.setInterrupt(); 1046 } 1047 } finally { 1048 enableSuspendAndPreempt(); 1049 } 1050 1051 // notify blocker after releasing interruptLock 1052 if (blocker != null) { 1053 blocker.postInterrupt(); 1054 } 1055 1056 // make available parking permit, unpark thread if parked 1057 unpark(); 1058 1059 // if thread is waiting in Object.wait then schedule to try to reenter 1060 int s = state(); 1061 if ((s == WAIT || s == TIMED_WAIT) && compareAndSetState(s, UNBLOCKED)) { 1062 submitRunContinuation(); 1063 } 1064 1065 } else { 1066 interrupted = true; 1067 carrierThread.setInterrupt(); 1068 setParkPermit(true); 1069 } 1070 } 1071 1072 @Override 1073 public boolean isInterrupted() { 1074 return interrupted; 1075 } 1076 1077 @Override 1078 boolean getAndClearInterrupt() { 1079 assert Thread.currentThread() == this; 1080 boolean oldValue = interrupted; 1081 if (oldValue) { 1082 disableSuspendAndPreempt(); 1083 try { 1084 synchronized (interruptLock) { 1085 interrupted = false; 1086 carrierThread.clearInterrupt(); 1087 } 1088 } finally { 1089 enableSuspendAndPreempt(); 1090 } 1091 } 1092 return oldValue; 1093 } 1094 1095 @Override 1096 Thread.State threadState() { 1097 int s = state(); 1098 switch (s & ~SUSPENDED) { 1099 case NEW: 1100 return Thread.State.NEW; 1101 case STARTED: 1102 // return NEW if thread container not yet set 1103 if (threadContainer() == null) { 1104 return Thread.State.NEW; 1105 } else { 1106 return Thread.State.RUNNABLE; 1107 } 1108 case UNPARKED: 1109 case UNBLOCKED: 1110 case YIELDED: 1111 // runnable, not mounted 1112 return Thread.State.RUNNABLE; 1113 case RUNNING: 1114 // if mounted then return state of carrier thread 1115 if (Thread.currentThread() != this) { 1116 disableSuspendAndPreempt(); 1117 try { 1118 synchronized (carrierThreadAccessLock()) { 1119 Thread carrierThread = this.carrierThread; 1120 if (carrierThread != null) { 1121 return carrierThread.threadState(); 1122 } 1123 } 1124 } finally { 1125 enableSuspendAndPreempt(); 1126 } 1127 } 1128 // runnable, mounted 1129 return Thread.State.RUNNABLE; 1130 case PARKING: 1131 case TIMED_PARKING: 1132 case WAITING: 1133 case TIMED_WAITING: 1134 case YIELDING: 1135 // runnable, in transition 1136 return Thread.State.RUNNABLE; 1137 case PARKED: 1138 case PINNED: 1139 case WAIT: 1140 return Thread.State.WAITING; 1141 case TIMED_PARKED: 1142 case TIMED_PINNED: 1143 case TIMED_WAIT: 1144 return Thread.State.TIMED_WAITING; 1145 case BLOCKING: 1146 case BLOCKED: 1147 return Thread.State.BLOCKED; 1148 case TERMINATED: 1149 return Thread.State.TERMINATED; 1150 default: 1151 throw new InternalError(); 1152 } 1153 } 1154 1155 @Override 1156 boolean alive() { 1157 int s = state; 1158 return (s != NEW && s != TERMINATED); 1159 } 1160 1161 @Override 1162 boolean isTerminated() { 1163 return (state == TERMINATED); 1164 } 1165 1166 @Override 1167 StackTraceElement[] asyncGetStackTrace() { 1168 StackTraceElement[] stackTrace; 1169 do { 1170 stackTrace = (carrierThread != null) 1171 ? super.asyncGetStackTrace() // mounted 1172 : tryGetStackTrace(); // unmounted 1173 if (stackTrace == null) { 1174 Thread.yield(); 1175 } 1176 } while (stackTrace == null); 1177 return stackTrace; 1178 } 1179 1180 /** 1181 * Returns the stack trace for this virtual thread if it is unmounted. 1182 * Returns null if the thread is mounted or in transition. 1183 */ 1184 private StackTraceElement[] tryGetStackTrace() { 1185 int initialState = state() & ~SUSPENDED; 1186 switch (initialState) { 1187 case NEW, STARTED, TERMINATED -> { 1188 return new StackTraceElement[0]; // unmounted, empty stack 1189 } 1190 case RUNNING, PINNED, TIMED_PINNED -> { 1191 return null; // mounted 1192 } 1193 case PARKED, TIMED_PARKED, BLOCKED, WAIT, TIMED_WAIT -> { 1194 // unmounted, not runnable 1195 } 1196 case UNPARKED, UNBLOCKED, YIELDED -> { 1197 // unmounted, runnable 1198 } 1199 case PARKING, TIMED_PARKING, BLOCKING, YIELDING, WAITING, TIMED_WAITING -> { 1200 return null; // in transition 1201 } 1202 default -> throw new InternalError("" + initialState); 1203 } 1204 1205 // thread is unmounted, prevent it from continuing 1206 int suspendedState = initialState | SUSPENDED; 1207 if (!compareAndSetState(initialState, suspendedState)) { 1208 return null; 1209 } 1210 1211 // get stack trace and restore state 1212 StackTraceElement[] stack; 1213 try { 1214 stack = cont.getStackTrace(); 1215 } finally { 1216 assert state == suspendedState; 1217 setState(initialState); 1218 } 1219 boolean resubmit = switch (initialState) { 1220 case UNPARKED, UNBLOCKED, YIELDED -> { 1221 // resubmit as task may have run while suspended 1222 yield true; 1223 } 1224 case PARKED, TIMED_PARKED -> { 1225 // resubmit if unparked while suspended 1226 yield parkPermit && compareAndSetState(initialState, UNPARKED); 1227 } 1228 case BLOCKED -> { 1229 // resubmit if unblocked while suspended 1230 yield blockPermit && compareAndSetState(BLOCKED, UNBLOCKED); 1231 } 1232 case WAIT, TIMED_WAIT -> { 1233 // resubmit if notified or interrupted while waiting (Object.wait) 1234 // waitTimeoutExpired will retry if the timed expired when suspended 1235 yield (notified || interrupted) && compareAndSetState(initialState, UNBLOCKED); 1236 } 1237 default -> throw new InternalError(); 1238 }; 1239 if (resubmit) { 1240 submitRunContinuation(); 1241 } 1242 return stack; 1243 } 1244 1245 @Override 1246 public String toString() { 1247 StringBuilder sb = new StringBuilder("VirtualThread[#"); 1248 sb.append(threadId()); 1249 String name = getName(); 1250 if (!name.isEmpty()) { 1251 sb.append(","); 1252 sb.append(name); 1253 } 1254 sb.append("]/"); 1255 1256 // add the carrier state and thread name when mounted 1257 boolean mounted; 1258 if (Thread.currentThread() == this) { 1259 mounted = appendCarrierInfo(sb); 1260 } else { 1261 disableSuspendAndPreempt(); 1262 try { 1263 synchronized (carrierThreadAccessLock()) { 1264 mounted = appendCarrierInfo(sb); 1265 } 1266 } finally { 1267 enableSuspendAndPreempt(); 1268 } 1269 } 1270 1271 // add virtual thread state when not mounted 1272 if (!mounted) { 1273 String stateAsString = threadState().toString(); 1274 sb.append(stateAsString.toLowerCase(Locale.ROOT)); 1275 } 1276 1277 return sb.toString(); 1278 } 1279 1280 /** 1281 * Appends the carrier state and thread name to the string buffer if mounted. 1282 * @return true if mounted, false if not mounted 1283 */ 1284 private boolean appendCarrierInfo(StringBuilder sb) { 1285 assert Thread.currentThread() == this || Thread.holdsLock(carrierThreadAccessLock()); 1286 Thread carrier = carrierThread; 1287 if (carrier != null) { 1288 String stateAsString = carrier.threadState().toString(); 1289 sb.append(stateAsString.toLowerCase(Locale.ROOT)); 1290 sb.append('@'); 1291 sb.append(carrier.getName()); 1292 return true; 1293 } else { 1294 return false; 1295 } 1296 } 1297 1298 @Override 1299 public int hashCode() { 1300 return (int) threadId(); 1301 } 1302 1303 @Override 1304 public boolean equals(Object obj) { 1305 return obj == this; 1306 } 1307 1308 /** 1309 * Returns the termination object, creating it if needed. 1310 */ 1311 private CountDownLatch getTermination() { 1312 CountDownLatch termination = this.termination; 1313 if (termination == null) { 1314 termination = new CountDownLatch(1); 1315 if (!U.compareAndSetReference(this, TERMINATION, null, termination)) { 1316 termination = this.termination; 1317 } 1318 } 1319 return termination; 1320 } 1321 1322 /** 1323 * Returns the lock object to synchronize on when accessing carrierThread. 1324 * The lock prevents carrierThread from being reset to null during unmount. 1325 */ 1326 private Object carrierThreadAccessLock() { 1327 // return interruptLock as unmount has to coordinate with interrupt 1328 return interruptLock; 1329 } 1330 1331 /** 1332 * Returns a lock object for coordinating timed-wait setup and timeout handling. 1333 */ 1334 private Object timedWaitLock() { 1335 // use this object for now to avoid the overhead of introducing another lock 1336 return runContinuation; 1337 } 1338 1339 /** 1340 * Disallow the current thread be suspended or preempted. 1341 */ 1342 private void disableSuspendAndPreempt() { 1343 notifyJvmtiDisableSuspend(true); 1344 Continuation.pin(); 1345 } 1346 1347 /** 1348 * Allow the current thread be suspended or preempted. 1349 */ 1350 private void enableSuspendAndPreempt() { 1351 Continuation.unpin(); 1352 notifyJvmtiDisableSuspend(false); 1353 } 1354 1355 // -- wrappers for get/set of state, parking permit, and carrier thread -- 1356 1357 private int state() { 1358 return state; // volatile read 1359 } 1360 1361 private void setState(int newValue) { 1362 state = newValue; // volatile write 1363 } 1364 1365 private boolean compareAndSetState(int expectedValue, int newValue) { 1366 return U.compareAndSetInt(this, STATE, expectedValue, newValue); 1367 } 1368 1369 private boolean compareAndSetOnWaitingList(boolean expectedValue, boolean newValue) { 1370 return U.compareAndSetBoolean(this, ON_WAITING_LIST, expectedValue, newValue); 1371 } 1372 1373 private void setParkPermit(boolean newValue) { 1374 if (parkPermit != newValue) { 1375 parkPermit = newValue; 1376 } 1377 } 1378 1379 private boolean getAndSetParkPermit(boolean newValue) { 1380 if (parkPermit != newValue) { 1381 return U.getAndSetBoolean(this, PARK_PERMIT, newValue); 1382 } else { 1383 return newValue; 1384 } 1385 } 1386 1387 private void setCarrierThread(Thread carrier) { 1388 // U.putReferenceRelease(this, CARRIER_THREAD, carrier); 1389 this.carrierThread = carrier; 1390 } 1391 1392 // -- JVM TI support -- 1393 1394 @IntrinsicCandidate 1395 @JvmtiMountTransition 1396 private native void notifyJvmtiStart(); 1397 1398 @IntrinsicCandidate 1399 @JvmtiMountTransition 1400 private native void notifyJvmtiEnd(); 1401 1402 @IntrinsicCandidate 1403 @JvmtiMountTransition 1404 private native void notifyJvmtiMount(boolean hide); 1405 1406 @IntrinsicCandidate 1407 @JvmtiMountTransition 1408 private native void notifyJvmtiUnmount(boolean hide); 1409 1410 @IntrinsicCandidate 1411 private static native void notifyJvmtiDisableSuspend(boolean enter); 1412 1413 private static native void registerNatives(); 1414 static { 1415 registerNatives(); 1416 1417 // ensure VTHREAD_GROUP is created, may be accessed by JVMTI 1418 var group = Thread.virtualThreadGroup(); 1419 } 1420 1421 /** 1422 * Creates the default ForkJoinPool scheduler. 1423 */ 1424 private static ForkJoinPool createDefaultScheduler() { 1425 ForkJoinWorkerThreadFactory factory = pool -> new CarrierThread(pool); 1426 int parallelism, maxPoolSize, minRunnable; 1427 String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism"); 1428 String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize"); 1429 String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable"); 1430 if (parallelismValue != null) { 1431 parallelism = Integer.parseInt(parallelismValue); 1432 } else { 1433 parallelism = Runtime.getRuntime().availableProcessors(); 1434 } 1435 if (maxPoolSizeValue != null) { 1436 maxPoolSize = Integer.parseInt(maxPoolSizeValue); 1437 parallelism = Integer.min(parallelism, maxPoolSize); 1438 } else { 1439 maxPoolSize = Integer.max(parallelism, 256); 1440 } 1441 if (minRunnableValue != null) { 1442 minRunnable = Integer.parseInt(minRunnableValue); 1443 } else { 1444 minRunnable = Integer.max(parallelism / 2, 1); 1445 } 1446 Thread.UncaughtExceptionHandler handler = (t, e) -> { }; 1447 boolean asyncMode = true; // FIFO 1448 return new ForkJoinPool(parallelism, factory, handler, asyncMode, 1449 0, maxPoolSize, minRunnable, pool -> true, 30, SECONDS); 1450 } 1451 1452 /** 1453 * Schedule a runnable task to run after a delay. 1454 */ 1455 private Future<?> schedule(Runnable command, long delay, TimeUnit unit) { 1456 if (scheduler instanceof ForkJoinPool pool) { 1457 return pool.schedule(command, delay, unit); 1458 } else { 1459 return DelayedTaskSchedulers.schedule(command, delay, unit); 1460 } 1461 } 1462 1463 /** 1464 * Supports scheduling a runnable task to run after a delay. It uses a number 1465 * of ScheduledThreadPoolExecutor instances to reduce contention on the delayed 1466 * work queue used. This class is used when using a custom scheduler. 1467 */ 1468 private static class DelayedTaskSchedulers { 1469 private static final ScheduledExecutorService[] INSTANCE = createDelayedTaskSchedulers(); 1470 1471 static Future<?> schedule(Runnable command, long delay, TimeUnit unit) { 1472 long tid = Thread.currentThread().threadId(); 1473 int index = (int) tid & (INSTANCE.length - 1); 1474 return INSTANCE[index].schedule(command, delay, unit); 1475 } 1476 1477 private static ScheduledExecutorService[] createDelayedTaskSchedulers() { 1478 String propName = "jdk.virtualThreadScheduler.timerQueues"; 1479 String propValue = System.getProperty(propName); 1480 int queueCount; 1481 if (propValue != null) { 1482 queueCount = Integer.parseInt(propValue); 1483 if (queueCount != Integer.highestOneBit(queueCount)) { 1484 throw new RuntimeException("Value of " + propName + " must be power of 2"); 1485 } 1486 } else { 1487 int ncpus = Runtime.getRuntime().availableProcessors(); 1488 queueCount = Math.max(Integer.highestOneBit(ncpus / 4), 1); 1489 } 1490 var schedulers = new ScheduledExecutorService[queueCount]; 1491 for (int i = 0; i < queueCount; i++) { 1492 ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor) 1493 Executors.newScheduledThreadPool(1, task -> { 1494 Thread t = InnocuousThread.newThread("VirtualThread-unparker", task); 1495 t.setDaemon(true); 1496 return t; 1497 }); 1498 stpe.setRemoveOnCancelPolicy(true); 1499 schedulers[i] = stpe; 1500 } 1501 return schedulers; 1502 } 1503 } 1504 1505 /** 1506 * Schedule virtual threads that are ready to be scheduled after they blocked on 1507 * monitor enter. 1508 */ 1509 private static void unblockVirtualThreads() { 1510 while (true) { 1511 VirtualThread vthread = takeVirtualThreadListToUnblock(); 1512 while (vthread != null) { 1513 assert vthread.onWaitingList; 1514 VirtualThread nextThread = vthread.next; 1515 1516 // remove from list and unblock 1517 vthread.next = null; 1518 boolean changed = vthread.compareAndSetOnWaitingList(true, false); 1519 assert changed; 1520 vthread.unblock(); 1521 1522 vthread = nextThread; 1523 } 1524 } 1525 } 1526 1527 /** 1528 * Retrieves the list of virtual threads that are waiting to be unblocked, waiting 1529 * if necessary until a list of one or more threads becomes available. 1530 */ 1531 private static native VirtualThread takeVirtualThreadListToUnblock(); 1532 1533 static { 1534 var unblocker = InnocuousThread.newThread("VirtualThread-unblocker", 1535 VirtualThread::unblockVirtualThreads); 1536 unblocker.setDaemon(true); 1537 unblocker.start(); 1538 } 1539 } --- EOF ---