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