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