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                 && (state() == TIMED_PARKED)
1034                 && compareAndSetState(TIMED_PARKED, UNPARKED)) {
1035             lazySubmitRunContinuation();
1036         }
1037     }
1038 
1039     /**
1040      * Invoked by FJP worker thread or STPE thread when wait timeout expires.
1041      * If the virtual thread is in timed-wait then this method will unblock the thread
1042      * and submit its task so that it continues and attempts to reenter the monitor.
1043      * This method does nothing if the thread has been woken by notify or interrupt.
1044      */
1045     private void waitTimeoutExpired(byte seqNo) {
1046         assert !Thread.currentThread().isVirtual();
1047 
1048         synchronized (timedWaitLock()) {
1049             if (seqNo != timedWaitSeqNo) {
1050                 // this timeout task is for a past timed-wait
1051                 return;
1052             }
1053             if (compareAndSetState(TIMED_WAIT, UNBLOCKED)) {
1054                 lazySubmitRunContinuation();
1055             }
1056         }
1057     }
1058 
1059     /**
1060      * Attempts to yield the current virtual thread (Thread.yield).
1061      */
1062     void tryYield() {
1063         assert Thread.currentThread() == this;
1064         setState(YIELDING);
1065         boolean yielded = false;
1066         try {
1067             yielded = yieldContinuation();  // may throw
1068         } finally {
1069             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
1070             if (!yielded) {
1071                 assert state() == YIELDING;
1072                 setState(RUNNING);
1073             }
1074         }
1075     }
1076 
1077     /**
1078      * Sleep the current thread for the given sleep time (in nanoseconds). If
1079      * nanos is 0 then the thread will attempt to yield.
1080      *
1081      * @implNote This implementation parks the thread for the given sleeping time
1082      * and will therefore be observed in PARKED state during the sleep. Parking
1083      * will consume the parking permit so this method makes available the parking
1084      * permit after the sleep. This may be observed as a spurious, but benign,
1085      * wakeup when the thread subsequently attempts to park.
1086      *
1087      * @param nanos the maximum number of nanoseconds to sleep
1088      * @throws InterruptedException if interrupted while sleeping
1089      */
1090     void sleepNanos(long nanos) throws InterruptedException {
1091         assert Thread.currentThread() == this && nanos >= 0;
1092         if (getAndClearInterrupt())
1093             throw new InterruptedException();
1094         if (nanos == 0) {
1095             tryYield();
1096         } else {
1097             // park for the sleep time
1098             try {
1099                 long remainingNanos = nanos;
1100                 long startNanos = System.nanoTime();
1101                 while (remainingNanos > 0) {
1102                     parkNanos(remainingNanos);
1103                     if (getAndClearInterrupt()) {
1104                         throw new InterruptedException();
1105                     }
1106                     remainingNanos = nanos - (System.nanoTime() - startNanos);
1107                 }
1108             } finally {
1109                 // may have been unparked while sleeping
1110                 setParkPermit(true);
1111             }
1112         }
1113     }
1114 
1115     /**
1116      * Waits up to {@code nanos} nanoseconds for this virtual thread to terminate.
1117      * A timeout of {@code 0} means to wait forever.
1118      *
1119      * @throws InterruptedException if interrupted while waiting
1120      * @return true if the thread has terminated
1121      */
1122     boolean joinNanos(long nanos) throws InterruptedException {
1123         if (state() == TERMINATED)
1124             return true;
1125 
1126         // ensure termination object exists, then re-check state
1127         CountDownLatch termination = getTermination();
1128         if (state() == TERMINATED)
1129             return true;
1130 
1131         // wait for virtual thread to terminate
1132         if (nanos == 0) {
1133             termination.await();
1134         } else {
1135             boolean terminated = termination.await(nanos, NANOSECONDS);
1136             if (!terminated) {
1137                 // waiting time elapsed
1138                 return false;
1139             }
1140         }
1141         assert state() == TERMINATED;
1142         return true;
1143     }
1144 
1145     @Override
1146     void blockedOn(Interruptible b) {
1147         disableSuspendAndPreempt();
1148         try {
1149             super.blockedOn(b);
1150         } finally {
1151             enableSuspendAndPreempt();
1152         }
1153     }
1154 
1155     @Override
1156     public void interrupt() {
1157         if (Thread.currentThread() != this) {
1158             // if current thread is a virtual thread then prevent it from being
1159             // suspended or unmounted when entering or holding interruptLock
1160             Interruptible blocker;
1161             disableSuspendAndPreempt();
1162             try {
1163                 synchronized (interruptLock) {
1164                     interrupted = true;
1165                     blocker = nioBlocker();
1166                     if (blocker != null) {
1167                         blocker.interrupt(this);
1168                     }
1169 
1170                     // interrupt carrier thread if mounted
1171                     Thread carrier = carrierThread;
1172                     if (carrier != null) carrier.setInterrupt();
1173                 }
1174             } finally {
1175                 enableSuspendAndPreempt();
1176             }
1177 
1178             // notify blocker after releasing interruptLock
1179             if (blocker != null) {
1180                 blocker.postInterrupt();
1181             }
1182 
1183             // make available parking permit, unpark thread if parked
1184             unpark();
1185 
1186             // if thread is waiting in Object.wait then schedule to try to reenter
1187             int s = state();
1188             if ((s == WAIT || s == TIMED_WAIT) && compareAndSetState(s, UNBLOCKED)) {
1189                 submitRunContinuation();
1190             }
1191 
1192         } else {
1193             interrupted = true;
1194             carrierThread.setInterrupt();
1195             setParkPermit(true);
1196         }
1197     }
1198 
1199     @Override
1200     public boolean isInterrupted() {
1201         return interrupted;
1202     }
1203 
1204     @Override
1205     boolean getAndClearInterrupt() {
1206         assert Thread.currentThread() == this;
1207         boolean oldValue = interrupted;
1208         if (oldValue) {
1209             disableSuspendAndPreempt();
1210             try {
1211                 synchronized (interruptLock) {
1212                     interrupted = false;
1213                     carrierThread.clearInterrupt();
1214                 }
1215             } finally {
1216                 enableSuspendAndPreempt();
1217             }
1218         }
1219         return oldValue;
1220     }
1221 
1222     @Override
1223     Thread.State threadState() {
1224         switch (state()) {
1225             case NEW:
1226                 return Thread.State.NEW;
1227             case STARTED:
1228                 // return NEW if thread container not yet set
1229                 if (threadContainer() == null) {
1230                     return Thread.State.NEW;
1231                 } else {
1232                     return Thread.State.RUNNABLE;
1233                 }
1234             case UNPARKED:
1235             case UNBLOCKED:
1236             case YIELDED:
1237                 // runnable, not mounted
1238                 return Thread.State.RUNNABLE;
1239             case RUNNING:
1240                 // if mounted then return state of carrier thread
1241                 if (Thread.currentThread() != this) {
1242                     disableSuspendAndPreempt();
1243                     try {
1244                         synchronized (carrierThreadAccessLock()) {
1245                             Thread carrierThread = this.carrierThread;
1246                             if (carrierThread != null) {
1247                                 return carrierThread.threadState();
1248                             }
1249                         }
1250                     } finally {
1251                         enableSuspendAndPreempt();
1252                     }
1253                 }
1254                 // runnable, mounted
1255                 return Thread.State.RUNNABLE;
1256             case PARKING:
1257             case TIMED_PARKING:
1258             case WAITING:
1259             case TIMED_WAITING:
1260             case YIELDING:
1261                 // runnable, in transition
1262                 return Thread.State.RUNNABLE;
1263             case PARKED:
1264             case PINNED:
1265             case WAIT:
1266                 return Thread.State.WAITING;
1267             case TIMED_PARKED:
1268             case TIMED_PINNED:
1269             case TIMED_WAIT:
1270                 return Thread.State.TIMED_WAITING;
1271             case BLOCKING:
1272             case BLOCKED:
1273                 return Thread.State.BLOCKED;
1274             case TERMINATED:
1275                 return Thread.State.TERMINATED;
1276             default:
1277                 throw new InternalError();
1278         }
1279     }
1280 
1281     @Override
1282     boolean alive() {
1283         int s = state;
1284         return (s != NEW && s != TERMINATED);
1285     }
1286 
1287     @Override
1288     boolean isTerminated() {
1289         return (state == TERMINATED);
1290     }
1291 
1292     @Override
1293     public String toString() {
1294         StringBuilder sb = new StringBuilder("VirtualThread[#");
1295         sb.append(threadId());
1296         String name = getName();
1297         if (!name.isEmpty()) {
1298             sb.append(",");
1299             sb.append(name);
1300         }
1301         sb.append("]/");
1302 
1303         // add the carrier state and thread name when mounted
1304         boolean mounted;
1305         if (Thread.currentThread() == this) {
1306             mounted = appendCarrierInfo(sb);
1307         } else {
1308             disableSuspendAndPreempt();
1309             try {
1310                 synchronized (carrierThreadAccessLock()) {
1311                     mounted = appendCarrierInfo(sb);
1312                 }
1313             } finally {
1314                 enableSuspendAndPreempt();
1315             }
1316         }
1317 
1318         // add virtual thread state when not mounted
1319         if (!mounted) {
1320             String stateAsString = threadState().toString();
1321             sb.append(stateAsString.toLowerCase(Locale.ROOT));
1322         }
1323 
1324         return sb.toString();
1325     }
1326 
1327     /**
1328      * Appends the carrier state and thread name to the string buffer if mounted.
1329      * @return true if mounted, false if not mounted
1330      */
1331     private boolean appendCarrierInfo(StringBuilder sb) {
1332         assert Thread.currentThread() == this || Thread.holdsLock(carrierThreadAccessLock());
1333         Thread carrier = carrierThread;
1334         if (carrier != null) {
1335             String stateAsString = carrier.threadState().toString();
1336             sb.append(stateAsString.toLowerCase(Locale.ROOT));
1337             sb.append('@');
1338             sb.append(carrier.getName());
1339             return true;
1340         } else {
1341             return false;
1342         }
1343     }
1344 
1345     @Override
1346     public int hashCode() {
1347         return (int) threadId();
1348     }
1349 
1350     @Override
1351     public boolean equals(Object obj) {
1352         return obj == this;
1353     }
1354 
1355     /**
1356      * Returns the termination object, creating it if needed.
1357      */
1358     private CountDownLatch getTermination() {
1359         CountDownLatch termination = this.termination;
1360         if (termination == null) {
1361             termination = new CountDownLatch(1);
1362             if (!U.compareAndSetReference(this, TERMINATION, null, termination)) {
1363                 termination = this.termination;
1364             }
1365         }
1366         return termination;
1367     }
1368 
1369     /**
1370      * Returns the lock object to synchronize on when accessing carrierThread.
1371      * The lock prevents carrierThread from being reset to null during unmount.
1372      */
1373     private Object carrierThreadAccessLock() {
1374         // return interruptLock as unmount has to coordinate with interrupt
1375         return interruptLock;
1376     }
1377 
1378     /**
1379      * Returns a lock object for coordinating timed-wait setup and timeout handling.
1380      */
1381     private Object timedWaitLock() {
1382         // use this object for now to avoid the overhead of introducing another lock
1383         return runContinuation;
1384     }
1385 
1386     /**
1387      * Disallow the current thread be suspended or preempted.
1388      */
1389     private void disableSuspendAndPreempt() {
1390         notifyJvmtiDisableSuspend(true);
1391         Continuation.pin();
1392     }
1393 
1394     /**
1395      * Allow the current thread be suspended or preempted.
1396      */
1397     private void enableSuspendAndPreempt() {
1398         Continuation.unpin();
1399         notifyJvmtiDisableSuspend(false);
1400     }
1401 
1402     // -- wrappers for get/set of state, parking permit, and carrier thread --
1403 
1404     private int state() {
1405         return state;  // volatile read
1406     }
1407 
1408     private void setState(int newValue) {
1409         state = newValue;  // volatile write
1410     }
1411 
1412     private boolean compareAndSetState(int expectedValue, int newValue) {
1413         return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1414     }
1415 
1416     private boolean compareAndSetOnWaitingList(boolean expectedValue, boolean newValue) {
1417         return U.compareAndSetBoolean(this, ON_WAITING_LIST, expectedValue, newValue);
1418     }
1419 
1420     private void setParkPermit(boolean newValue) {
1421         if (parkPermit != newValue) {
1422             parkPermit = newValue;
1423         }
1424     }
1425 
1426     private boolean getAndSetParkPermit(boolean newValue) {
1427         if (parkPermit != newValue) {
1428             return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1429         } else {
1430             return newValue;
1431         }
1432     }
1433 
1434     private void setCarrierThread(Thread carrier) {
1435         // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1436         this.carrierThread = carrier;
1437     }
1438 
1439     // The following four methods notify the VM when a "transition" starts and ends.
1440     // A "mount transition" embodies the steps to transfer control from a platform
1441     // thread to a virtual thread, changing the thread identity, and starting or
1442     // resuming the virtual thread's continuation on the carrier.
1443     // An "unmount transition" embodies the steps to transfer control from a virtual
1444     // thread to its carrier, suspending the virtual thread's continuation, and
1445     // restoring the thread identity to the platform thread.
1446     // The notifications to the VM are necessary in order to coordinate with functions
1447     // (JVMTI mostly) that disable transitions for one or all virtual threads. Starting
1448     // a transition may block if transitions are disabled. Ending a transition may
1449     // notify a thread that is waiting to disable transitions. The notifications are
1450     // also used to post JVMTI events for virtual thread start and end.
1451 
1452     @IntrinsicCandidate
1453     @JvmtiMountTransition
1454     private native void endFirstTransition();
1455 
1456     @IntrinsicCandidate
1457     @JvmtiMountTransition
1458     private native void startFinalTransition();
1459 
1460     @IntrinsicCandidate
1461     @JvmtiMountTransition
1462     private native void startTransition(boolean is_mount);
1463 
1464     @IntrinsicCandidate
1465     @JvmtiMountTransition
1466     private native void endTransition(boolean is_mount);
1467 
1468     @IntrinsicCandidate
1469     private static native void notifyJvmtiDisableSuspend(boolean enter);
1470 
1471     private static native void registerNatives();
1472     static {
1473         registerNatives();
1474 
1475         // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1476         var group = Thread.virtualThreadGroup();
1477 
1478         // ensure event class is initialized
1479         try {
1480             MethodHandles.lookup().ensureInitialized(VirtualThreadParkEvent.class);
1481         } catch (IllegalAccessException e) {
1482             throw new ExceptionInInitializerError(e);
1483         }
1484     }
1485 
1486     /**
1487      * Loads a VirtualThreadScheduler with the given class name. The class must be public
1488      * in an exported package, with public one-arg or no-arg constructor, and be visible
1489      * to the system class loader.
1490      * @param delegate the scheduler that the custom scheduler may delegate to
1491      * @param cn the class name of the custom scheduler
1492      */
1493     private static VirtualThreadScheduler loadCustomScheduler(VirtualThreadScheduler delegate, String cn) {
1494         VirtualThreadScheduler scheduler;
1495         try {
1496             Class<?> clazz = Class.forName(cn, true, ClassLoader.getSystemClassLoader());
1497             // 1-arg constructor
1498             try {
1499                 Constructor<?> ctor = clazz.getConstructor(VirtualThreadScheduler.class);
1500                 return (VirtualThreadScheduler) ctor.newInstance(delegate);
1501             } catch (NoSuchMethodException e) {
1502                 // 0-arg constructor
1503                 Constructor<?> ctor = clazz.getConstructor();
1504                 scheduler = (VirtualThreadScheduler) ctor.newInstance();
1505             }
1506         } catch (Exception ex) {
1507             throw new Error(ex);
1508         }
1509         System.err.println("WARNING: Using custom default scheduler, this is an experimental feature!");
1510         return scheduler;
1511     }
1512 
1513     /**
1514      * Creates the built-in ForkJoinPool scheduler.
1515      * @param wrapped true if wrapped by a custom default scheduler
1516      */
1517     private static BuiltinScheduler createBuiltinScheduler(boolean wrapped) {
1518         int parallelism, maxPoolSize, minRunnable;
1519         String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1520         String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1521         String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1522         if (parallelismValue != null) {
1523             parallelism = Integer.parseInt(parallelismValue);
1524         } else {
1525             parallelism = Runtime.getRuntime().availableProcessors();
1526         }
1527         if (maxPoolSizeValue != null) {
1528             maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1529             parallelism = Integer.min(parallelism, maxPoolSize);
1530         } else {
1531             maxPoolSize = Integer.max(parallelism, 256);
1532         }
1533         if (minRunnableValue != null) {
1534             minRunnable = Integer.parseInt(minRunnableValue);
1535         } else {
1536             minRunnable = Integer.max(parallelism / 2, 1);
1537         }
1538         return new BuiltinScheduler(parallelism, maxPoolSize, minRunnable, wrapped);
1539     }
1540 
1541     /**
1542      * The built-in ForkJoinPool scheduler.
1543      */
1544     private static class BuiltinScheduler
1545             extends ForkJoinPool implements VirtualThreadScheduler {
1546 
1547         BuiltinScheduler(int parallelism, int maxPoolSize, int minRunnable, boolean wrapped) {
1548             ForkJoinWorkerThreadFactory factory = wrapped
1549                     ? ForkJoinPool.defaultForkJoinWorkerThreadFactory
1550                     : CarrierThread::new;
1551             Thread.UncaughtExceptionHandler handler = (t, e) -> { };
1552             boolean asyncMode = true; // FIFO
1553             super(parallelism, factory, handler, asyncMode,
1554                     0, maxPoolSize, minRunnable, pool -> true, 30, SECONDS);
1555         }
1556 
1557         private void adaptAndExecute(Runnable task) {
1558             execute(ForkJoinTask.adapt(task));
1559         }
1560 
1561         @Override
1562         public void onStart(VirtualThreadTask task) {
1563             adaptAndExecute(task);
1564         }
1565 
1566         @Override
1567         public void onContinue(VirtualThreadTask task) {
1568             adaptAndExecute(task);
1569         }
1570 
1571         /**
1572          * Wraps the scheduler to avoid leaking a direct reference with
1573          * {@link VirtualThreadScheduler#current()}.
1574          */
1575         VirtualThreadScheduler createExternalView() {
1576             BuiltinScheduler builtin = this;
1577             return new VirtualThreadScheduler() {
1578                 private void execute(VirtualThreadTask task) {
1579                     var vthread = (VirtualThread) task.thread();
1580                     VirtualThreadScheduler scheduler = vthread.scheduler;
1581                     if (scheduler == this || scheduler == DEFAULT_SCHEDULER) {
1582                         builtin.adaptAndExecute(task);
1583                     } else {
1584                         throw new IllegalArgumentException();
1585                     }
1586                 }
1587                 @Override
1588                 public void onStart(VirtualThreadTask task) {
1589                     execute(task);
1590                 }
1591                 @Override
1592                 public void onContinue(VirtualThreadTask task) {
1593                     execute(task);
1594                 }
1595                 @Override
1596                 public String toString() {
1597                     return builtin.toString();
1598                 }
1599             };
1600         }
1601     }
1602 
1603     /**
1604      * Schedule a runnable task to run after a delay.
1605      */
1606     private Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1607         if (scheduler == BUILTIN_SCHEDULER) {
1608             return BUILTIN_SCHEDULER.schedule(command, delay, unit);
1609         } else {
1610             return DelayedTaskSchedulers.schedule(command, delay, unit);
1611         }
1612     }
1613 
1614     /**
1615      * Supports scheduling a runnable task to run after a delay. It uses a number
1616      * of ScheduledThreadPoolExecutor instances to reduce contention on the delayed
1617      * work queue used. This class is used when using a custom scheduler.
1618      */
1619     private static class DelayedTaskSchedulers {
1620         private static final ScheduledExecutorService[] INSTANCE = createDelayedTaskSchedulers();
1621 
1622         static Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1623             long tid = Thread.currentThread().threadId();
1624             int index = (int) tid & (INSTANCE.length - 1);
1625             return INSTANCE[index].schedule(command, delay, unit);
1626         }
1627 
1628         private static ScheduledExecutorService[] createDelayedTaskSchedulers() {
1629             String propName = "jdk.virtualThreadScheduler.timerQueues";
1630             String propValue = System.getProperty(propName);
1631             int queueCount;
1632             if (propValue != null) {
1633                 queueCount = Integer.parseInt(propValue);
1634                 if (queueCount != Integer.highestOneBit(queueCount)) {
1635                     throw new RuntimeException("Value of " + propName + " must be power of 2");
1636                 }
1637             } else {
1638                 int ncpus = Runtime.getRuntime().availableProcessors();
1639                 queueCount = Math.max(Integer.highestOneBit(ncpus / 4), 1);
1640             }
1641             var schedulers = new ScheduledExecutorService[queueCount];
1642             for (int i = 0; i < queueCount; i++) {
1643                 ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor)
1644                     Executors.newScheduledThreadPool(1, task -> {
1645                         Thread t = InnocuousThread.newThread("VirtualThread-unparker", task);
1646                         t.setDaemon(true);
1647                         return t;
1648                     });
1649                 stpe.setRemoveOnCancelPolicy(true);
1650                 schedulers[i] = stpe;
1651             }
1652             return schedulers;
1653         }
1654     }
1655 
1656     /**
1657      * Schedule virtual threads that are ready to be scheduled after they blocked on
1658      * monitor enter.
1659      */
1660     private static void unblockVirtualThreads() {
1661         while (true) {
1662             VirtualThread vthread = takeVirtualThreadListToUnblock();
1663             while (vthread != null) {
1664                 assert vthread.onWaitingList;
1665                 VirtualThread nextThread = vthread.next;
1666 
1667                 // remove from list and unblock
1668                 vthread.next = null;
1669                 boolean changed = vthread.compareAndSetOnWaitingList(true, false);
1670                 assert changed;
1671                 vthread.unblock();
1672 
1673                 vthread = nextThread;
1674             }
1675         }
1676     }
1677 
1678     /**
1679      * Retrieves the list of virtual threads that are waiting to be unblocked, waiting
1680      * if necessary until a list of one or more threads becomes available.
1681      */
1682     private static native VirtualThread takeVirtualThreadListToUnblock();
1683 
1684     static {
1685         var unblocker = InnocuousThread.newThread("VirtualThread-unblocker",
1686                 VirtualThread::unblockVirtualThreads);
1687         unblocker.setDaemon(true);
1688         unblocker.start();
1689     }
1690 }