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