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