1 /*
   2  * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.lang;
  26 
  27 import java.lang.invoke.MethodHandles;
  28 import java.lang.invoke.VarHandle;
  29 import java.lang.reflect.Constructor;
  30 import java.util.Locale;
  31 import java.util.Objects;
  32 import java.util.concurrent.CountDownLatch;

  33 import java.util.concurrent.Executors;
  34 import java.util.concurrent.ForkJoinPool;

  35 import java.util.concurrent.ForkJoinTask;
  36 import java.util.concurrent.Future;
  37 import java.util.concurrent.LinkedTransferQueue;
  38 import java.util.concurrent.RejectedExecutionException;
  39 import java.util.concurrent.ScheduledExecutorService;
  40 import java.util.concurrent.ScheduledFuture;
  41 import java.util.concurrent.ScheduledThreadPoolExecutor;
  42 import java.util.concurrent.ThreadFactory;
  43 import java.util.concurrent.ThreadPoolExecutor;
  44 import java.util.concurrent.TimeUnit;
  45 import jdk.internal.event.VirtualThreadEndEvent;
  46 import jdk.internal.event.VirtualThreadParkEvent;
  47 import jdk.internal.event.VirtualThreadStartEvent;
  48 import jdk.internal.event.VirtualThreadSubmitFailedEvent;
  49 import jdk.internal.invoke.MhUtil;
  50 import jdk.internal.misc.CarrierThread;
  51 import jdk.internal.misc.InnocuousThread;
  52 import jdk.internal.misc.Unsafe;
  53 import jdk.internal.vm.Continuation;
  54 import jdk.internal.vm.ContinuationScope;
  55 import jdk.internal.vm.StackableScope;
  56 import jdk.internal.vm.ThreadContainer;
  57 import jdk.internal.vm.ThreadContainers;
  58 import jdk.internal.vm.annotation.ChangesCurrentThread;
  59 import jdk.internal.vm.annotation.Hidden;
  60 import jdk.internal.vm.annotation.IntrinsicCandidate;
  61 import jdk.internal.vm.annotation.JvmtiHideEvents;
  62 import jdk.internal.vm.annotation.JvmtiMountTransition;
  63 import jdk.internal.vm.annotation.ReservedStackAccess;
  64 import sun.nio.ch.Interruptible;
  65 import static java.util.concurrent.TimeUnit.*;
  66 
  67 /**
  68  * A thread that is scheduled by the Java virtual machine rather than the operating system.
  69  */
  70 final class VirtualThread extends BaseVirtualThread {
  71     private static final Unsafe U = Unsafe.getUnsafe();
  72     private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
  73 
  74     private static final VirtualThreadScheduler BUILTIN_SCHEDULER;
  75     private static final VirtualThreadScheduler DEFAULT_SCHEDULER;
  76     private static final VirtualThreadScheduler EXTERNAL_VIEW;
  77     private static final boolean USE_STPE;
  78     static {
  79         // experimental
  80         String propValue = System.getProperty("jdk.virtualThreadScheduler.implClass");
  81         if (propValue != null) {
  82             VirtualThreadScheduler builtinScheduler = createBuiltinScheduler(true);
  83             VirtualThreadScheduler externalView = createExternalView(builtinScheduler);
  84             VirtualThreadScheduler defaultScheduler = loadCustomScheduler(externalView, propValue);
  85             BUILTIN_SCHEDULER = builtinScheduler;
  86             DEFAULT_SCHEDULER = defaultScheduler;
  87             EXTERNAL_VIEW = externalView;
  88         } else {
  89             var builtinScheduler = createBuiltinScheduler(false);
  90             BUILTIN_SCHEDULER = builtinScheduler;
  91             DEFAULT_SCHEDULER = builtinScheduler;
  92             EXTERNAL_VIEW = createExternalView(builtinScheduler);
  93         }
  94         USE_STPE = Boolean.getBoolean("jdk.virtualThreadScheduler.useSTPE");
  95     }
  96 
  97     private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
  98     private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
  99     private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
 100     private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
 101     private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList");
 102 
 103     // scheduler and continuation
 104     private final VirtualThreadScheduler scheduler;
 105     private final Continuation cont;
 106     private final VThreadRunner runContinuation;
 107 
 108     // virtual thread state, accessed by VM
 109     private volatile int state;
 110 
 111     /*
 112      * Virtual thread state transitions:
 113      *
 114      *      NEW -> STARTED         // Thread.start, schedule to run
 115      *  STARTED -> TERMINATED      // failed to start
 116      *  STARTED -> RUNNING         // first run
 117      *  RUNNING -> TERMINATED      // done
 118      *
 119      *  RUNNING -> PARKING         // Thread parking with LockSupport.park
 120      *  PARKING -> PARKED          // cont.yield successful, parked indefinitely
 121      *   PARKED -> UNPARKED        // unparked, may be scheduled to continue
 122      * UNPARKED -> RUNNING         // continue execution after park
 123      *
 124      *  PARKING -> RUNNING         // cont.yield failed, need to park on carrier
 125      *  RUNNING -> PINNED          // park on carrier
 126      *   PINNED -> RUNNING         // unparked, continue execution on same carrier
 127      *
 128      *       RUNNING -> TIMED_PARKING   // Thread parking with LockSupport.parkNanos
 129      * TIMED_PARKING -> TIMED_PARKED    // cont.yield successful, timed-parked
 130      *  TIMED_PARKED -> UNPARKED        // unparked, may be scheduled to continue
 131      *
 132      * TIMED_PARKING -> RUNNING         // cont.yield failed, need to park on carrier
 133      *       RUNNING -> TIMED_PINNED    // park on carrier
 134      *  TIMED_PINNED -> RUNNING         // unparked, continue execution on same carrier
 135      *
 136      *   RUNNING -> BLOCKING       // blocking on monitor enter
 137      *  BLOCKING -> BLOCKED        // blocked on monitor enter
 138      *   BLOCKED -> UNBLOCKED      // unblocked, may be scheduled to continue
 139      * UNBLOCKED -> RUNNING        // continue execution after blocked on monitor enter
 140      *
 141      *   RUNNING -> WAITING        // transitional state during wait on monitor
 142      *   WAITING -> WAIT           // waiting on monitor
 143      *      WAIT -> BLOCKED        // notified, waiting to be unblocked by monitor owner
 144      *      WAIT -> UNBLOCKED      // interrupted
 145      *
 146      *       RUNNING -> TIMED_WAITING   // transition state during timed-waiting on monitor
 147      * TIMED_WAITING -> TIMED_WAIT      // timed-waiting on monitor
 148      *    TIMED_WAIT -> BLOCKED         // notified, waiting to be unblocked by monitor owner
 149      *    TIMED_WAIT -> UNBLOCKED       // timed-out/interrupted
 150      *
 151      *  RUNNING -> YIELDING        // Thread.yield
 152      * YIELDING -> YIELDED         // cont.yield successful, may be scheduled to continue
 153      * YIELDING -> RUNNING         // cont.yield failed
 154      *  YIELDED -> RUNNING         // continue execution after Thread.yield
 155      */
 156     private static final int NEW      = 0;
 157     private static final int STARTED  = 1;
 158     private static final int RUNNING  = 2;     // runnable-mounted
 159 
 160     // untimed and timed parking
 161     private static final int PARKING       = 3;
 162     private static final int PARKED        = 4;     // unmounted
 163     private static final int PINNED        = 5;     // mounted
 164     private static final int TIMED_PARKING = 6;
 165     private static final int TIMED_PARKED  = 7;     // unmounted
 166     private static final int TIMED_PINNED  = 8;     // mounted
 167     private static final int UNPARKED      = 9;     // unmounted but runnable
 168 
 169     // Thread.yield
 170     private static final int YIELDING = 10;
 171     private static final int YIELDED  = 11;         // unmounted but runnable
 172 
 173     // monitor enter
 174     private static final int BLOCKING  = 12;
 175     private static final int BLOCKED   = 13;        // unmounted
 176     private static final int UNBLOCKED = 14;        // unmounted but runnable
 177 
 178     // monitor wait/timed-wait
 179     private static final int WAITING       = 15;
 180     private static final int WAIT          = 16;    // waiting in Object.wait
 181     private static final int TIMED_WAITING = 17;
 182     private static final int TIMED_WAIT    = 18;    // waiting in timed-Object.wait
 183 
 184     private static final int TERMINATED = 99;  // final state
 185 
 186     // parking permit made available by LockSupport.unpark
 187     private volatile boolean parkPermit;
 188 
 189     // blocking permit made available by unblocker thread when another thread exits monitor
 190     private volatile boolean blockPermit;
 191 
 192     // true when on the list of virtual threads waiting to be unblocked
 193     private volatile boolean onWaitingList;
 194 
 195     // next virtual thread on the list of virtual threads waiting to be unblocked
 196     private volatile VirtualThread next;
 197 
 198     // notified by Object.notify/notifyAll while waiting in Object.wait
 199     private volatile boolean notified;
 200 
 201     // true when waiting in Object.wait, false for VM internal uninterruptible Object.wait
 202     private volatile boolean interruptibleWait;
 203 
 204     // timed-wait support
 205     private byte timedWaitSeqNo;
 206 
 207     // timeout for timed-park and timed-wait, only accessed on current/carrier thread
 208     private long timeout;
 209 
 210     // timer task for timed-park and timed-wait, only accessed on current/carrier thread
 211     private Future<?> timeoutTask;
 212 
 213     // carrier thread when mounted, accessed by VM
 214     private volatile Thread carrierThread;
 215 
 216     // termination object when joining, created lazily if needed
 217     private volatile CountDownLatch termination;
 218 
 219     /**
 220      * Return the built-in scheduler.
 221      * @param trusted true if caller is trusted, false if not trusted
 222      */
 223     static VirtualThreadScheduler builtinScheduler(boolean trusted) {
 224         return trusted ? BUILTIN_SCHEDULER : EXTERNAL_VIEW;
 225     }
 226 
 227     /**
 228      * Returns the default scheduler, usually the same as the built-in scheduler.
 229      */
 230     static VirtualThreadScheduler defaultScheduler() {
 231         return DEFAULT_SCHEDULER;
 232     }
 233 
 234     /**
 235      * Returns the continuation scope used for virtual threads.
 236      */
 237     static ContinuationScope continuationScope() {
 238         return VTHREAD_SCOPE;
 239     }
 240 
 241     /**
 242      * Returns the task to start/continue this virtual thread.
 243      */
 244     VirtualThreadTask virtualThreadTask() {
 245         return runContinuation;
 246     }
 247 
 248     /**
 249      * Creates a new {@code VirtualThread} to run the given task with the given scheduler.
 250      *
 251      * @param scheduler the scheduler or null for default scheduler
 252      * @param preferredCarrier the preferred carrier or null
 253      * @param name thread name
 254      * @param characteristics characteristics
 255      * @param task the task to execute
 256      */
 257     VirtualThread(VirtualThreadScheduler scheduler,
 258                   Thread preferredCarrier,
 259                   String name,
 260                   int characteristics,
 261                   Runnable task) {
 262         super(name, characteristics, /*bound*/ false);
 263         Objects.requireNonNull(task);
 264 
 265         // use default scheduler if not provided
 266         if (scheduler == null) {
 267             scheduler = DEFAULT_SCHEDULER;
 268         } else if (scheduler == EXTERNAL_VIEW) {
 269             throw new UnsupportedOperationException();



 270         }

 271         this.scheduler = scheduler;
 272         this.cont = new VThreadContinuation(this, task);
 273 
 274         if (scheduler == BUILTIN_SCHEDULER) {
 275             this.runContinuation = new VThreadRunner(this);
 276         } else {
 277             this.runContinuation = new CustomSchedulerVThreadRunner(this, preferredCarrier);
 278         }
 279     }
 280 
 281     /**
 282      * The task to start/continue a virtual thread.
 283      */
 284     static non-sealed class VThreadRunner implements VirtualThreadTask {
 285         private final VirtualThread vthread;
 286         VThreadRunner(VirtualThread vthread) {
 287             this.vthread = vthread;
 288         }
 289         @Override
 290         public final Thread thread() {
 291             return vthread;
 292         }
 293         @Override
 294         public final void run() {
 295             vthread.runContinuation();;
 296         }
 297         @Override
 298         public Thread preferredCarrier() {
 299             throw new UnsupportedOperationException();
 300         }
 301         @Override
 302         public Object attach(Object att) {
 303             throw new UnsupportedOperationException();
 304         }
 305         @Override
 306         public Object attachment() {
 307             throw new UnsupportedOperationException();
 308         }
 309     }
 310 
 311     /**
 312      * The task to start/continue a virtual thread when using a custom scheduler.
 313      */
 314     static final class CustomSchedulerVThreadRunner extends VThreadRunner {
 315         private static final VarHandle ATT =
 316                 MhUtil.findVarHandle(MethodHandles.lookup(), "att", Object.class);
 317         private final Thread preferredCarrier;
 318         private volatile Object att;
 319         CustomSchedulerVThreadRunner(VirtualThread vthread, Thread preferredCarrier) {
 320             super(vthread);
 321             this.preferredCarrier = preferredCarrier;
 322         }
 323         @Override
 324         public Thread preferredCarrier() {
 325             return preferredCarrier;
 326         }
 327         @Override
 328         public Object attach(Object att) {
 329             return ATT.getAndSet(this, att);
 330         }
 331         @Override
 332         public Object attachment() {
 333             return att;
 334         }
 335     }
 336 
 337     /**
 338      * The continuation that a virtual thread executes.
 339      */
 340     private static class VThreadContinuation extends Continuation {
 341         VThreadContinuation(VirtualThread vthread, Runnable task) {
 342             super(VTHREAD_SCOPE, wrap(vthread, task));
 343         }
 344         @Override
 345         protected void onPinned(Continuation.Pinned reason) {
 346         }
 347         private static Runnable wrap(VirtualThread vthread, Runnable task) {
 348             return new Runnable() {
 349                 @Hidden
 350                 @JvmtiHideEvents
 351                 public void run() {
 352                     vthread.endFirstTransition();
 353                     try {
 354                         vthread.run(task);
 355                     } finally {
 356                         vthread.startFinalTransition();
 357                     }
 358                 }
 359             };
 360         }
 361     }
 362 
 363     /**
 364      * Runs or continues execution on the current thread. The virtual thread is mounted
 365      * on the current thread before the task runs or continues. It unmounts when the
 366      * task completes or yields.
 367      */
 368     @ChangesCurrentThread // allow mount/unmount to be inlined
 369     private void runContinuation() {
 370         // the carrier must be a platform thread
 371         if (Thread.currentThread().isVirtual()) {
 372             throw new WrongThreadException();
 373         }
 374 
 375         // set state to RUNNING
 376         int initialState = state();
 377         if (initialState == STARTED || initialState == UNPARKED
 378                 || initialState == UNBLOCKED || initialState == YIELDED) {
 379             // newly started or continue after parking/blocking/Thread.yield
 380             if (!compareAndSetState(initialState, RUNNING)) {
 381                 return;
 382             }
 383             // consume permit when continuing after parking or blocking. If continue
 384             // after a timed-park or timed-wait then the timeout task is cancelled.
 385             if (initialState == UNPARKED) {
 386                 cancelTimeoutTask();
 387                 setParkPermit(false);
 388             } else if (initialState == UNBLOCKED) {
 389                 cancelTimeoutTask();
 390                 blockPermit = false;
 391             }
 392         } else {
 393             // not runnable
 394             return;
 395         }
 396 
 397         mount();
 398         try {
 399             cont.run();
 400         } finally {
 401             unmount();
 402             if (cont.isDone()) {
 403                 afterDone();
 404             } else {
 405                 afterYield();
 406             }
 407         }
 408     }
 409 
 410     /**
 411      * Cancel timeout task when continuing after timed-park or timed-wait.
 412      * The timeout task may be executing, or may have already completed.
 413      */
 414     private void cancelTimeoutTask() {
 415         if (timeoutTask != null) {
 416             timeoutTask.cancel(false);
 417             timeoutTask = null;
 418         }
 419     }
 420 
 421     /**
 422      * Submits the runContinuation task to the scheduler. For the built-in scheduler,
 423      * the task will be pushed to the local queue if possible, otherwise it will be
 424      * pushed to an external submission queue.













 425      * @param retryOnOOME true to retry indefinitely if OutOfMemoryError is thrown
 426      * @throws RejectedExecutionException
 427      */
 428     private void submitRunContinuation(boolean retryOnOOME) {
 429         boolean done = false;
 430         while (!done) {
 431             try {
 432                 // Pin the continuation to prevent the virtual thread from unmounting
 433                 // when submitting a task. For the default scheduler this ensures that
 434                 // the carrier doesn't change when pushing a task. For other schedulers
 435                 // it avoids deadlock that could arise due to carriers and virtual
 436                 // threads contending for a lock.
 437                 if (currentThread().isVirtual()) {
 438                     Continuation.pin();
 439                     try {
 440                         scheduler.onContinue(runContinuation);
 441                     } finally {
 442                         Continuation.unpin();
 443                     }
 444                 } else {
 445                     scheduler.onContinue(runContinuation);
 446                 }
 447                 done = true;
 448             } catch (RejectedExecutionException ree) {
 449                 submitFailed(ree);
 450                 throw ree;
 451             } catch (OutOfMemoryError e) {
 452                 if (retryOnOOME) {
 453                     U.park(false, 100_000_000); // 100ms
 454                 } else {
 455                     throw e;
 456                 }
 457             }
 458         }
 459     }
 460 


















 461     /**
 462      * Submits the runContinuation task to the scheduler. For the default scheduler,
 463      * and calling it on a worker thread, the task will be pushed to the local queue,
 464      * otherwise it will be pushed to an external submission queue.
 465      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 466      * @throws RejectedExecutionException
 467      */
 468     private void submitRunContinuation() {
 469         submitRunContinuation(true);
 470     }
 471 
 472     /**
 473      * Invoked from a carrier thread to lazy submit the runContinuation task to the
 474      * carrier's local queue if the queue is empty. If not empty, or invoked by a thread
 475      * for a custom scheduler, then it just submits the task to the scheduler.
 476      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 477      * @throws RejectedExecutionException
 478      * @see ForkJoinPool#lazySubmit(ForkJoinTask)
 479      */
 480     private void lazySubmitRunContinuation() {
 481         assert !currentThread().isVirtual();
 482         if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {

 483             try {
 484                 ct.getPool().lazySubmit(ForkJoinTask.adapt(runContinuation));
 485             } catch (RejectedExecutionException ree) {
 486                 submitFailed(ree);
 487                 throw ree;
 488             } catch (OutOfMemoryError e) {
 489                 submitRunContinuation();
 490             }
 491         } else {
 492             submitRunContinuation();
 493         }
 494     }
 495 
 496     /**
 497      * Invoked from a carrier thread to externally submit the runContinuation task to the
 498      * scheduler. If invoked by a thread for a custom scheduler, then it just submits the
 499      * task to the scheduler.
 500      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 501      * @throws RejectedExecutionException
 502      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 503      */
 504     private void externalSubmitRunContinuation() {
 505         assert !currentThread().isVirtual();
 506         if (currentThread() instanceof CarrierThread ct) {
 507             try {
 508                 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
 509             } catch (RejectedExecutionException ree) {
 510                 submitFailed(ree);
 511                 throw ree;
 512             } catch (OutOfMemoryError e) {
 513                 submitRunContinuation();
 514             }
 515         } else {
 516             submitRunContinuation();
 517         }
 518     }
 519 
 520     /**
 521      * Invoked from Thread.start to externally submit the runContinuation task to the
 522      * scheduler. If this virtual thread is scheduled by the built-in scheduler,
 523      * and this method is called from a virtual thread scheduled by the built-in
 524      * scheduler, then it uses externalSubmit to ensure that the task is pushed to an
 525      * external submission queue rather than the local queue.
 526      * @throws RejectedExecutionException
 527      * @throws OutOfMemoryError
 528      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 529      */
 530     private void externalSubmitRunContinuationOrThrow() {
 531         try {
 532             if (currentThread().isVirtual()) {
 533                 // Pin the continuation to prevent the virtual thread from unmounting
 534                 // when submitting a task. This avoids deadlock that could arise due to
 535                 // carriers and virtual threads contending for a lock.
 536                 Continuation.pin();
 537                 try {
 538                     if (scheduler == BUILTIN_SCHEDULER
 539                             && currentCarrierThread() instanceof CarrierThread ct) {
 540                         ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
 541                     } else {
 542                         scheduler.onStart(runContinuation);
 543                     }
 544                 } finally {
 545                     Continuation.unpin();
 546                 }
 547             } else {
 548                 scheduler.onStart(runContinuation);
 549             }
 550         } catch (RejectedExecutionException ree) {
 551             submitFailed(ree);
 552             throw ree;
 553         }
 554     }
 555 
 556     /**
 557      * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
 558      */
 559     private void submitFailed(RejectedExecutionException ree) {
 560         var event = new VirtualThreadSubmitFailedEvent();
 561         if (event.isEnabled()) {
 562             event.javaThreadId = threadId();
 563             event.exceptionMessage = ree.getMessage();
 564             event.commit();
 565         }
 566     }
 567 
 568     /**
 569      * Runs a task in the context of this virtual thread.
 570      */
 571     private void run(Runnable task) {
 572         assert Thread.currentThread() == this && state == RUNNING;
 573 
 574         // emit JFR event if enabled
 575         if (VirtualThreadStartEvent.isTurnedOn()) {
 576             var event = new VirtualThreadStartEvent();
 577             event.javaThreadId = threadId();
 578             event.commit();
 579         }
 580 
 581         Object bindings = Thread.scopedValueBindings();
 582         try {
 583             runWith(bindings, task);
 584         } catch (Throwable exc) {
 585             dispatchUncaughtException(exc);
 586         } finally {
 587             // pop any remaining scopes from the stack, this may block
 588             StackableScope.popAll();
 589 
 590             // emit JFR event if enabled
 591             if (VirtualThreadEndEvent.isTurnedOn()) {
 592                 var event = new VirtualThreadEndEvent();
 593                 event.javaThreadId = threadId();
 594                 event.commit();
 595             }
 596         }
 597     }
 598 
 599     /**
 600      * Mounts this virtual thread onto the current platform thread. On
 601      * return, the current thread is the virtual thread.
 602      */
 603     @ChangesCurrentThread
 604     @ReservedStackAccess
 605     private void mount() {
 606         startTransition(/*mount*/true);
 607         // We assume following volatile accesses provide equivalent
 608         // of acquire ordering, otherwise we need U.loadFence() here.
 609 
 610         // sets the carrier thread
 611         Thread carrier = Thread.currentCarrierThread();
 612         setCarrierThread(carrier);
 613 
 614         // sync up carrier thread interrupted status if needed
 615         if (interrupted) {
 616             carrier.setInterrupt();
 617         } else if (carrier.isInterrupted()) {
 618             synchronized (interruptLock) {
 619                 // need to recheck interrupted status
 620                 if (!interrupted) {
 621                     carrier.clearInterrupt();
 622                 }
 623             }
 624         }
 625 
 626         // set Thread.currentThread() to return this virtual thread
 627         carrier.setCurrentThread(this);
 628     }
 629 
 630     /**
 631      * Unmounts this virtual thread from the carrier. On return, the
 632      * current thread is the current platform thread.
 633      */
 634     @ChangesCurrentThread
 635     @ReservedStackAccess
 636     private void unmount() {
 637         assert !Thread.holdsLock(interruptLock);
 638 
 639         // set Thread.currentThread() to return the platform thread
 640         Thread carrier = this.carrierThread;
 641         carrier.setCurrentThread(carrier);
 642 
 643         // break connection to carrier thread, synchronized with interrupt
 644         synchronized (interruptLock) {
 645             setCarrierThread(null);
 646         }
 647         carrier.clearInterrupt();
 648 
 649         // We assume previous volatile accesses provide equivalent
 650         // of release ordering, otherwise we need U.storeFence() here.
 651         endTransition(/*mount*/false);
 652     }
 653 
 654     /**
 655      * Invokes Continuation.yield, notifying JVMTI (if enabled) to hide frames until
 656      * the continuation continues.
 657      */
 658     @Hidden
 659     private boolean yieldContinuation() {
 660         startTransition(/*mount*/false);
 661         try {
 662             return Continuation.yield(VTHREAD_SCOPE);
 663         } finally {
 664             endTransition(/*mount*/true);
 665         }
 666     }
 667 
 668     /**
 669      * Invoked in the context of the carrier thread after the Continuation yields when
 670      * parking, blocking on monitor enter, Object.wait, or Thread.yield.
 671      */
 672     private void afterYield() {
 673         assert carrierThread == null;
 674 
 675         // re-adjust parallelism if the virtual thread yielded when compensating
 676         if (currentThread() instanceof CarrierThread ct) {
 677             ct.endBlocking();
 678         }
 679 
 680         int s = state();
 681 
 682         // LockSupport.park/parkNanos
 683         if (s == PARKING || s == TIMED_PARKING) {
 684             int newState;
 685             if (s == PARKING) {
 686                 setState(newState = PARKED);
 687             } else {
 688                 // schedule unpark
 689                 long timeout = this.timeout;
 690                 assert timeout > 0;
 691                 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS);
 692                 setState(newState = TIMED_PARKED);
 693             }
 694 
 695             // may have been unparked while parking
 696             if (parkPermit && compareAndSetState(newState, UNPARKED)) {
 697                 // lazy submit if local queue is empty
 698                 lazySubmitRunContinuation();
 699             }
 700             return;
 701         }
 702 
 703         // Thread.yield
 704         if (s == YIELDING) {
 705             setState(YIELDED);
 706 
 707             // external submit if there are no tasks in the local task queue
 708             if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
 709                 externalSubmitRunContinuation();
 710             } else {
 711                 submitRunContinuation();
 712             }
 713             return;
 714         }
 715 
 716         // blocking on monitorenter
 717         if (s == BLOCKING) {
 718             setState(BLOCKED);
 719 
 720             // may have been unblocked while blocking
 721             if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
 722                 // lazy submit if local queue is empty
 723                 lazySubmitRunContinuation();
 724             }
 725             return;
 726         }
 727 
 728         // Object.wait
 729         if (s == WAITING || s == TIMED_WAITING) {
 730             int newState;
 731             boolean blocked;
 732             boolean interruptible = interruptibleWait;
 733             if (s == WAITING) {
 734                 setState(newState = WAIT);
 735                 // may have been notified while in transition
 736                 blocked = notified && compareAndSetState(WAIT, BLOCKED);
 737             } else {
 738                 // For timed-wait, a timeout task is scheduled to execute. The timeout
 739                 // task will change the thread state to UNBLOCKED and submit the thread
 740                 // to the scheduler. A sequence number is used to ensure that the timeout
 741                 // task only unblocks the thread for this timed-wait. We synchronize with
 742                 // the timeout task to coordinate access to the sequence number and to
 743                 // ensure the timeout task doesn't execute until the thread has got to
 744                 // the TIMED_WAIT state.
 745                 long timeout = this.timeout;
 746                 assert timeout > 0;
 747                 synchronized (timedWaitLock()) {
 748                     byte seqNo = ++timedWaitSeqNo;
 749                     timeoutTask = schedule(() -> waitTimeoutExpired(seqNo), timeout, MILLISECONDS);
 750                     setState(newState = TIMED_WAIT);
 751                     // May have been notified while in transition. This must be done while
 752                     // holding the monitor to avoid changing the state of a new timed wait call.
 753                     blocked = notified && compareAndSetState(TIMED_WAIT, BLOCKED);
 754                 }
 755             }
 756 
 757             if (blocked) {
 758                 // may have been unblocked already
 759                 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
 760                     lazySubmitRunContinuation();
 761                 }
 762             } else {
 763                 // may have been interrupted while in transition to wait state
 764                 if (interruptible && interrupted && compareAndSetState(newState, UNBLOCKED)) {
 765                     lazySubmitRunContinuation();
 766                 }
 767             }
 768             return;
 769         }
 770 
 771         assert false;
 772     }
 773 
 774     /**
 775      * Invoked after the continuation completes.
 776      */
 777     private void afterDone() {
 778         afterDone(true);
 779     }
 780 
 781     /**
 782      * Invoked after the continuation completes (or start failed). Sets the thread
 783      * state to TERMINATED and notifies anyone waiting for the thread to terminate.
 784      *
 785      * @param notifyContainer true if its container should be notified
 786      */
 787     private void afterDone(boolean notifyContainer) {
 788         assert carrierThread == null;
 789         setState(TERMINATED);
 790 
 791         // notify anyone waiting for this virtual thread to terminate
 792         CountDownLatch termination = this.termination;
 793         if (termination != null) {
 794             assert termination.getCount() == 1;
 795             termination.countDown();
 796         }
 797 
 798         // notify container
 799         if (notifyContainer) {
 800             threadContainer().remove(this);
 801         }
 802 
 803         // clear references to thread locals
 804         clearReferences();
 805     }
 806 
 807     /**
 808      * Schedules this {@code VirtualThread} to execute.
 809      *
 810      * @throws IllegalStateException if the container is shutdown or closed
 811      * @throws IllegalThreadStateException if the thread has already been started
 812      * @throws RejectedExecutionException if the scheduler cannot accept a task
 813      */
 814     @Override
 815     void start(ThreadContainer container) {
 816         if (!compareAndSetState(NEW, STARTED)) {
 817             throw new IllegalThreadStateException("Already started");
 818         }
 819 
 820         // bind thread to container
 821         assert threadContainer() == null;
 822         setThreadContainer(container);
 823 
 824         // start thread
 825         boolean addedToContainer = false;
 826         boolean started = false;
 827         try {
 828             container.add(this);  // may throw
 829             addedToContainer = true;
 830 
 831             // scoped values may be inherited
 832             inheritScopedValueBindings(container);
 833 
 834             // submit task to run thread, using externalSubmit if possible
 835             externalSubmitRunContinuationOrThrow();
 836             started = true;
 837         } finally {
 838             if (!started) {
 839                 afterDone(addedToContainer);
 840             }
 841         }
 842     }
 843 
 844     @Override
 845     public void start() {
 846         start(ThreadContainers.root());
 847     }
 848 
 849     @Override
 850     public void run() {
 851         // do nothing
 852     }
 853 
 854     /**
 855      * Parks until unparked or interrupted. If already unparked then the parking
 856      * permit is consumed and this method completes immediately (meaning it doesn't
 857      * yield). It also completes immediately if the interrupted status is set.
 858      */
 859     @Override
 860     void park() {
 861         assert Thread.currentThread() == this;
 862 
 863         // complete immediately if parking permit available or interrupted
 864         if (getAndSetParkPermit(false) || interrupted)
 865             return;
 866 
 867         // park the thread
 868         boolean yielded = false;
 869         long eventStartTime = VirtualThreadParkEvent.eventStartTime();
 870         setState(PARKING);
 871         try {
 872             yielded = yieldContinuation();
 873         } catch (OutOfMemoryError e) {
 874             // park on carrier
 875         } finally {
 876             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 877             if (yielded) {
 878                 VirtualThreadParkEvent.offer(eventStartTime, Long.MIN_VALUE);
 879             } else {
 880                 assert state() == PARKING;
 881                 setState(RUNNING);
 882             }
 883         }
 884 
 885         // park on the carrier thread when pinned
 886         if (!yielded) {
 887             parkOnCarrierThread(false, 0);
 888         }
 889     }
 890 
 891     /**
 892      * Parks up to the given waiting time or until unparked or interrupted.
 893      * If already unparked then the parking permit is consumed and this method
 894      * completes immediately (meaning it doesn't yield). It also completes immediately
 895      * if the interrupted status is set or the waiting time is {@code <= 0}.
 896      *
 897      * @param nanos the maximum number of nanoseconds to wait.
 898      */
 899     @Override
 900     void parkNanos(long nanos) {
 901         assert Thread.currentThread() == this;
 902 
 903         // complete immediately if parking permit available or interrupted
 904         if (getAndSetParkPermit(false) || interrupted)
 905             return;
 906 
 907         // park the thread for the waiting time
 908         if (nanos > 0) {
 909             long startTime = System.nanoTime();
 910 
 911             // park the thread, afterYield will schedule the thread to unpark
 912             boolean yielded = false;
 913             long eventStartTime = VirtualThreadParkEvent.eventStartTime();
 914             timeout = nanos;
 915             setState(TIMED_PARKING);
 916             try {
 917                 yielded = yieldContinuation();
 918             } catch (OutOfMemoryError e) {
 919                 // park on carrier
 920             } finally {
 921                 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 922                 if (yielded) {
 923                     VirtualThreadParkEvent.offer(eventStartTime, nanos);
 924                 } else {
 925                     assert state() == TIMED_PARKING;
 926                     setState(RUNNING);
 927                 }
 928             }
 929 
 930             // park on carrier thread for remaining time when pinned (or OOME)
 931             if (!yielded) {
 932                 long remainingNanos = nanos - (System.nanoTime() - startTime);
 933                 parkOnCarrierThread(true, remainingNanos);
 934             }
 935         }
 936     }
 937 
 938     /**
 939      * Parks the current carrier thread up to the given waiting time or until
 940      * unparked or interrupted. If the virtual thread is interrupted then the
 941      * interrupted status will be propagated to the carrier thread.
 942      * @param timed true for a timed park, false for untimed
 943      * @param nanos the waiting time in nanoseconds
 944      */
 945     private void parkOnCarrierThread(boolean timed, long nanos) {
 946         assert state() == RUNNING;
 947 
 948         setState(timed ? TIMED_PINNED : PINNED);
 949         try {
 950             if (!parkPermit) {
 951                 if (!timed) {
 952                     U.park(false, 0);
 953                 } else if (nanos > 0) {
 954                     U.park(false, nanos);
 955                 }
 956             }
 957         } finally {
 958             setState(RUNNING);
 959         }
 960 
 961         // consume parking permit
 962         setParkPermit(false);
 963 
 964         // JFR jdk.VirtualThreadPinned event
 965         postPinnedEvent("LockSupport.park");
 966     }
 967 
 968     /**
 969      * Call into VM when pinned to record a JFR jdk.VirtualThreadPinned event.
 970      * Recording the event in the VM avoids having JFR event recorded in Java
 971      * with the same name, but different ID, to events recorded by the VM.
 972      */
 973     @Hidden
 974     private static native void postPinnedEvent(String op);
 975 
 976     /**
 977      * Re-enables this virtual thread for scheduling. If this virtual thread is parked
 978      * then its task is scheduled to continue, otherwise its next call to {@code park} or
 979      * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block.
 980      * @param lazySubmit to use lazySubmit if possible
 981      * @throws RejectedExecutionException if the scheduler cannot accept a task
 982      */
 983     private void unpark(boolean lazySubmit) {
 984         if (!getAndSetParkPermit(true) && currentThread() != this) {
 985             int s = state();
 986 
 987             // unparked while parked
 988             if ((s == PARKED || s == TIMED_PARKED) && compareAndSetState(s, UNPARKED)) {
 989                 if (lazySubmit) {
 990                     lazySubmitRunContinuation();
 991                 } else {
 992                     submitRunContinuation();
 993                 }
 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     @Override
1017     void unpark() {
1018         unpark(false);
1019     }
1020 
1021     /**
1022      * Invoked by unblocker thread to unblock this virtual thread.
1023      */
1024     private void unblock() {
1025         assert !Thread.currentThread().isVirtual();
1026         blockPermit = true;
1027         if (state() == BLOCKED && compareAndSetState(BLOCKED, UNBLOCKED)) {
1028             submitRunContinuation();
1029         }
1030     }
1031 
1032     /**
1033      * Invoked by FJP worker thread or STPE thread when park timeout expires.
1034      */
1035     private void parkTimeoutExpired() {
1036         assert !VirtualThread.currentThread().isVirtual();
1037         unpark(true);
1038     }
1039 
1040     /**
1041      * Invoked by FJP worker thread or STPE thread when wait timeout expires.
1042      * If the virtual thread is in timed-wait then this method will unblock the thread
1043      * and submit its task so that it continues and attempts to reenter the monitor.
1044      * This method does nothing if the thread has been woken by notify or interrupt.
1045      */
1046     private void waitTimeoutExpired(byte seqNo) {
1047         assert !Thread.currentThread().isVirtual();
1048 
1049         synchronized (timedWaitLock()) {
1050             if (seqNo != timedWaitSeqNo) {
1051                 // this timeout task is for a past timed-wait
1052                 return;
1053             }
1054             if (!compareAndSetState(TIMED_WAIT, UNBLOCKED)) {
1055                 // already notified (or interrupted)
1056                 return;
1057             }
1058         }
1059 
1060         lazySubmitRunContinuation();
1061     }
1062 
1063     /**
1064      * Attempts to yield the current virtual thread (Thread.yield).
1065      */
1066     void tryYield() {
1067         assert Thread.currentThread() == this;
1068         setState(YIELDING);
1069         boolean yielded = false;
1070         try {
1071             yielded = yieldContinuation();  // may throw
1072         } finally {
1073             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
1074             if (!yielded) {
1075                 assert state() == YIELDING;
1076                 setState(RUNNING);
1077             }
1078         }
1079     }
1080 
1081     /**
1082      * Sleep the current thread for the given sleep time (in nanoseconds). If
1083      * nanos is 0 then the thread will attempt to yield.
1084      *
1085      * @implNote This implementation parks the thread for the given sleeping time
1086      * and will therefore be observed in PARKED state during the sleep. Parking
1087      * will consume the parking permit so this method makes available the parking
1088      * permit after the sleep. This may be observed as a spurious, but benign,
1089      * wakeup when the thread subsequently attempts to park.
1090      *
1091      * @param nanos the maximum number of nanoseconds to sleep
1092      * @throws InterruptedException if interrupted while sleeping
1093      */
1094     void sleepNanos(long nanos) throws InterruptedException {
1095         assert Thread.currentThread() == this && nanos >= 0;
1096         if (getAndClearInterrupt())
1097             throw new InterruptedException();
1098         if (nanos == 0) {
1099             tryYield();
1100         } else {
1101             // park for the sleep time
1102             try {
1103                 long remainingNanos = nanos;
1104                 long startNanos = System.nanoTime();
1105                 while (remainingNanos > 0) {
1106                     parkNanos(remainingNanos);
1107                     if (getAndClearInterrupt()) {
1108                         throw new InterruptedException();
1109                     }
1110                     remainingNanos = nanos - (System.nanoTime() - startNanos);
1111                 }
1112             } finally {
1113                 // may have been unparked while sleeping
1114                 setParkPermit(true);
1115             }
1116         }
1117     }
1118 
1119     /**
1120      * Waits up to {@code nanos} nanoseconds for this virtual thread to terminate.
1121      * A timeout of {@code 0} means to wait forever.
1122      *
1123      * @throws InterruptedException if interrupted while waiting
1124      * @return true if the thread has terminated
1125      */
1126     boolean joinNanos(long nanos) throws InterruptedException {
1127         if (state() == TERMINATED)
1128             return true;
1129 
1130         // ensure termination object exists, then re-check state
1131         CountDownLatch termination = getTermination();
1132         if (state() == TERMINATED)
1133             return true;
1134 
1135         // wait for virtual thread to terminate
1136         if (nanos == 0) {
1137             termination.await();
1138         } else {
1139             boolean terminated = termination.await(nanos, NANOSECONDS);
1140             if (!terminated) {
1141                 // waiting time elapsed
1142                 return false;
1143             }
1144         }
1145         assert state() == TERMINATED;
1146         return true;
1147     }
1148 
1149     @Override
1150     void blockedOn(Interruptible b) {
1151         disableSuspendAndPreempt();
1152         try {
1153             super.blockedOn(b);
1154         } finally {
1155             enableSuspendAndPreempt();
1156         }
1157     }
1158 
1159     @Override
1160     public void interrupt() {
1161         if (Thread.currentThread() != this) {
1162             // if current thread is a virtual thread then prevent it from being
1163             // suspended or unmounted when entering or holding interruptLock
1164             Interruptible blocker;
1165             disableSuspendAndPreempt();
1166             try {
1167                 synchronized (interruptLock) {
1168                     interrupted = true;
1169                     blocker = nioBlocker();
1170                     if (blocker != null) {
1171                         blocker.interrupt(this);
1172                     }
1173 
1174                     // interrupt carrier thread if mounted
1175                     Thread carrier = carrierThread;
1176                     if (carrier != null) carrier.setInterrupt();
1177                 }
1178             } finally {
1179                 enableSuspendAndPreempt();
1180             }
1181 
1182             // notify blocker after releasing interruptLock
1183             if (blocker != null) {
1184                 blocker.postInterrupt();
1185             }
1186 
1187             // make available parking permit, unpark thread if parked
1188             unpark();
1189 
1190             // if thread is waiting in Object.wait then schedule to try to reenter
1191             int s = state();
1192             if ((s == WAIT || s == TIMED_WAIT) && compareAndSetState(s, UNBLOCKED)) {
1193                 submitRunContinuation();
1194             }
1195 
1196         } else {
1197             interrupted = true;
1198             carrierThread.setInterrupt();
1199             setParkPermit(true);
1200         }
1201     }
1202 
1203     @Override
1204     public boolean isInterrupted() {
1205         return interrupted;
1206     }
1207 
1208     @Override
1209     boolean getAndClearInterrupt() {
1210         assert Thread.currentThread() == this;
1211         boolean oldValue = interrupted;
1212         if (oldValue) {
1213             disableSuspendAndPreempt();
1214             try {
1215                 synchronized (interruptLock) {
1216                     interrupted = false;
1217                     carrierThread.clearInterrupt();
1218                 }
1219             } finally {
1220                 enableSuspendAndPreempt();
1221             }
1222         }
1223         return oldValue;
1224     }
1225 
1226     @Override
1227     Thread.State threadState() {
1228         switch (state()) {
1229             case NEW:
1230                 return Thread.State.NEW;
1231             case STARTED:
1232                 // return NEW if thread container not yet set
1233                 if (threadContainer() == null) {
1234                     return Thread.State.NEW;
1235                 } else {
1236                     return Thread.State.RUNNABLE;
1237                 }
1238             case UNPARKED:
1239             case UNBLOCKED:
1240             case YIELDED:
1241                 // runnable, not mounted
1242                 return Thread.State.RUNNABLE;
1243             case RUNNING:
1244                 // if mounted then return state of carrier thread
1245                 if (Thread.currentThread() != this) {
1246                     disableSuspendAndPreempt();
1247                     try {
1248                         synchronized (carrierThreadAccessLock()) {
1249                             Thread carrierThread = this.carrierThread;
1250                             if (carrierThread != null) {
1251                                 return carrierThread.threadState();
1252                             }
1253                         }
1254                     } finally {
1255                         enableSuspendAndPreempt();
1256                     }
1257                 }
1258                 // runnable, mounted
1259                 return Thread.State.RUNNABLE;
1260             case PARKING:
1261             case TIMED_PARKING:
1262             case WAITING:
1263             case TIMED_WAITING:
1264             case YIELDING:
1265                 // runnable, in transition
1266                 return Thread.State.RUNNABLE;
1267             case PARKED:
1268             case PINNED:
1269             case WAIT:
1270                 return Thread.State.WAITING;
1271             case TIMED_PARKED:
1272             case TIMED_PINNED:
1273             case TIMED_WAIT:
1274                 return Thread.State.TIMED_WAITING;
1275             case BLOCKING:
1276             case BLOCKED:
1277                 return Thread.State.BLOCKED;
1278             case TERMINATED:
1279                 return Thread.State.TERMINATED;
1280             default:
1281                 throw new InternalError();
1282         }
1283     }
1284 
1285     @Override
1286     boolean alive() {
1287         int s = state;
1288         return (s != NEW && s != TERMINATED);
1289     }
1290 
1291     @Override
1292     boolean isTerminated() {
1293         return (state == TERMINATED);
1294     }
1295 
1296     @Override
1297     public String toString() {
1298         StringBuilder sb = new StringBuilder("VirtualThread[#");
1299         sb.append(threadId());
1300         String name = getName();
1301         if (!name.isEmpty()) {
1302             sb.append(",");
1303             sb.append(name);
1304         }
1305         sb.append("]/");
1306 
1307         // add the carrier state and thread name when mounted
1308         boolean mounted;
1309         if (Thread.currentThread() == this) {
1310             mounted = appendCarrierInfo(sb);
1311         } else {
1312             disableSuspendAndPreempt();
1313             try {
1314                 synchronized (carrierThreadAccessLock()) {
1315                     mounted = appendCarrierInfo(sb);
1316                 }
1317             } finally {
1318                 enableSuspendAndPreempt();
1319             }
1320         }
1321 
1322         // add virtual thread state when not mounted
1323         if (!mounted) {
1324             String stateAsString = threadState().toString();
1325             sb.append(stateAsString.toLowerCase(Locale.ROOT));
1326         }
1327 
1328         return sb.toString();
1329     }
1330 
1331     /**
1332      * Appends the carrier state and thread name to the string buffer if mounted.
1333      * @return true if mounted, false if not mounted
1334      */
1335     private boolean appendCarrierInfo(StringBuilder sb) {
1336         assert Thread.currentThread() == this || Thread.holdsLock(carrierThreadAccessLock());
1337         Thread carrier = carrierThread;
1338         if (carrier != null) {
1339             String stateAsString = carrier.threadState().toString();
1340             sb.append(stateAsString.toLowerCase(Locale.ROOT));
1341             sb.append('@');
1342             sb.append(carrier.getName());
1343             return true;
1344         } else {
1345             return false;
1346         }
1347     }
1348 
1349     @Override
1350     public int hashCode() {
1351         return (int) threadId();
1352     }
1353 
1354     @Override
1355     public boolean equals(Object obj) {
1356         return obj == this;
1357     }
1358 
1359     /**
1360      * Returns the termination object, creating it if needed.
1361      */
1362     private CountDownLatch getTermination() {
1363         CountDownLatch termination = this.termination;
1364         if (termination == null) {
1365             termination = new CountDownLatch(1);
1366             if (!U.compareAndSetReference(this, TERMINATION, null, termination)) {
1367                 termination = this.termination;
1368             }
1369         }
1370         return termination;
1371     }
1372 
1373     /**
1374      * Returns the lock object to synchronize on when accessing carrierThread.
1375      * The lock prevents carrierThread from being reset to null during unmount.
1376      */
1377     private Object carrierThreadAccessLock() {
1378         // return interruptLock as unmount has to coordinate with interrupt
1379         return interruptLock;
1380     }
1381 
1382     /**
1383      * Returns a lock object for coordinating timed-wait setup and timeout handling.
1384      */
1385     private Object timedWaitLock() {
1386         // use this object for now to avoid the overhead of introducing another lock
1387         return runContinuation;
1388     }
1389 
1390     /**
1391      * Disallow the current thread be suspended or preempted.
1392      */
1393     private void disableSuspendAndPreempt() {
1394         notifyJvmtiDisableSuspend(true);
1395         Continuation.pin();
1396     }
1397 
1398     /**
1399      * Allow the current thread be suspended or preempted.
1400      */
1401     private void enableSuspendAndPreempt() {
1402         Continuation.unpin();
1403         notifyJvmtiDisableSuspend(false);
1404     }
1405 
1406     // -- wrappers for get/set of state, parking permit, and carrier thread --
1407 
1408     private int state() {
1409         return state;  // volatile read
1410     }
1411 
1412     private void setState(int newValue) {
1413         state = newValue;  // volatile write
1414     }
1415 
1416     private boolean compareAndSetState(int expectedValue, int newValue) {
1417         return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1418     }
1419 
1420     private boolean compareAndSetOnWaitingList(boolean expectedValue, boolean newValue) {
1421         return U.compareAndSetBoolean(this, ON_WAITING_LIST, expectedValue, newValue);
1422     }
1423 
1424     private void setParkPermit(boolean newValue) {
1425         if (parkPermit != newValue) {
1426             parkPermit = newValue;
1427         }
1428     }
1429 
1430     private boolean getAndSetParkPermit(boolean newValue) {
1431         if (parkPermit != newValue) {
1432             return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1433         } else {
1434             return newValue;
1435         }
1436     }
1437 
1438     private void setCarrierThread(Thread carrier) {
1439         // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1440         this.carrierThread = carrier;
1441     }
1442 
1443     // The following four methods notify the VM when a "transition" starts and ends.
1444     // A "mount transition" embodies the steps to transfer control from a platform
1445     // thread to a virtual thread, changing the thread identity, and starting or
1446     // resuming the virtual thread's continuation on the carrier.
1447     // An "unmount transition" embodies the steps to transfer control from a virtual
1448     // thread to its carrier, suspending the virtual thread's continuation, and
1449     // restoring the thread identity to the platform thread.
1450     // The notifications to the VM are necessary in order to coordinate with functions
1451     // (JVMTI mostly) that disable transitions for one or all virtual threads. Starting
1452     // a transition may block if transitions are disabled. Ending a transition may
1453     // notify a thread that is waiting to disable transitions. The notifications are
1454     // also used to post JVMTI events for virtual thread start and end.
1455 
1456     @IntrinsicCandidate
1457     @JvmtiMountTransition
1458     private native void endFirstTransition();
1459 
1460     @IntrinsicCandidate
1461     @JvmtiMountTransition
1462     private native void startFinalTransition();
1463 
1464     @IntrinsicCandidate
1465     @JvmtiMountTransition
1466     private native void startTransition(boolean mount);
1467 
1468     @IntrinsicCandidate
1469     @JvmtiMountTransition
1470     private native void endTransition(boolean mount);
1471 
1472     @IntrinsicCandidate
1473     private static native void notifyJvmtiDisableSuspend(boolean enter);
1474 
1475     private static native void registerNatives();
1476     static {
1477         registerNatives();
1478 
1479         // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1480         var group = Thread.virtualThreadGroup();
1481 
1482         // ensure event class is initialized
1483         try {
1484             MethodHandles.lookup().ensureInitialized(VirtualThreadParkEvent.class);
1485         } catch (IllegalAccessException e) {
1486             throw new ExceptionInInitializerError(e);
1487         }
1488     }
1489 
1490     /**
1491      * Loads a VirtualThreadScheduler with the given class name. The class must be public
1492      * in an exported package, with public one-arg or no-arg constructor, and be visible
1493      * to the system class loader.
1494      * @param delegate the scheduler that the custom scheduler may delegate to
1495      * @param cn the class name of the custom scheduler
1496      */
1497     private static VirtualThreadScheduler loadCustomScheduler(VirtualThreadScheduler delegate, String cn) {
1498         VirtualThreadScheduler scheduler;
1499         try {
1500             Class<?> clazz = Class.forName(cn, true, ClassLoader.getSystemClassLoader());
1501             // 1-arg constructor
1502             try {
1503                 Constructor<?> ctor = clazz.getConstructor(VirtualThreadScheduler.class);
1504                 return (VirtualThreadScheduler) ctor.newInstance(delegate);
1505             } catch (NoSuchMethodException e) {
1506                 // 0-arg constructor
1507                 Constructor<?> ctor = clazz.getConstructor();
1508                 scheduler = (VirtualThreadScheduler) ctor.newInstance();
1509             }
1510         } catch (Exception ex) {
1511             throw new Error(ex);
1512         }
1513         System.err.println("WARNING: Using custom default scheduler, this is an experimental feature!");
1514         return scheduler;
1515     }
1516 
1517     /**
1518      * Creates the built-in ForkJoinPool scheduler.
1519      * @param wrapped true if wrapped by a custom default scheduler
1520      */
1521     private static VirtualThreadScheduler createBuiltinScheduler(boolean wrapped) {

1522         int parallelism, maxPoolSize, minRunnable;
1523         String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1524         String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1525         String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1526         if (parallelismValue != null) {
1527             parallelism = Integer.parseInt(parallelismValue);
1528         } else {
1529             parallelism = Runtime.getRuntime().availableProcessors();
1530         }
1531         if (maxPoolSizeValue != null) {
1532             maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1533             parallelism = Integer.min(parallelism, maxPoolSize);
1534         } else {
1535             maxPoolSize = Integer.max(parallelism, 256);
1536         }
1537         if (minRunnableValue != null) {
1538             minRunnable = Integer.parseInt(minRunnableValue);
1539         } else {
1540             minRunnable = Integer.max(parallelism / 2, 1);
1541         }
1542         if (Boolean.getBoolean("jdk.virtualThreadScheduler.useTPE")) {
1543             return new BuiltinThreadPoolExecutorScheduler(parallelism);
1544         } else {
1545             return new BuiltinForkJoinPoolScheduler(parallelism, maxPoolSize, minRunnable, wrapped);
1546         }
1547     }
1548 
1549     /**
1550      * The built-in ForkJoinPool scheduler.
1551      */
1552     private static class BuiltinForkJoinPoolScheduler
1553             extends ForkJoinPool implements VirtualThreadScheduler {
1554 
1555         BuiltinForkJoinPoolScheduler(int parallelism, int maxPoolSize, int minRunnable, boolean wrapped) {
1556             ForkJoinWorkerThreadFactory factory = wrapped
1557                     ? ForkJoinPool.defaultForkJoinWorkerThreadFactory
1558                     : CarrierThread::new;
1559             Thread.UncaughtExceptionHandler handler = (t, e) -> { };
1560             boolean asyncMode = true; // FIFO
1561             super(parallelism, factory, handler, asyncMode,
1562                     0, maxPoolSize, minRunnable, pool -> true, 30L, SECONDS);
1563         }
1564 
1565         @Override
1566         public void onStart(VirtualThreadTask task) {
1567             execute(ForkJoinTask.adapt(task));
1568         }
1569 
1570         @Override
1571         public void onContinue(VirtualThreadTask task) {
1572             execute(ForkJoinTask.adapt(task));
1573         }
1574 
1575         @Override
1576         public ScheduledFuture<?> schedule(Runnable task, long delay, TimeUnit unit) {
1577             return super.schedule(task, delay, unit);
1578         }
1579     }
1580 
1581     /**
1582      * Built-in ThreadPoolExecutor scheduler.
1583      */
1584     private static class BuiltinThreadPoolExecutorScheduler
1585             extends ThreadPoolExecutor implements VirtualThreadScheduler {
1586 
1587         BuiltinThreadPoolExecutorScheduler(int maxPoolSize) {
1588             ThreadFactory factory = task -> {
1589                 Thread t = InnocuousThread.newThread(task);
1590                 t.setDaemon(true);
1591                 return t;
1592             };
1593             super(maxPoolSize, maxPoolSize,
1594                     0L, SECONDS,
1595                     new LinkedTransferQueue<>(),
1596                     factory);
1597         }
1598 
1599         @Override
1600         public void onStart(VirtualThreadTask task) {
1601             execute(task);
1602         }
1603 
1604         @Override
1605         public void onContinue(VirtualThreadTask task) {
1606             execute(task);
1607         }
1608     }
1609 
1610     /**
1611      * Wraps the scheduler to avoid leaking a direct reference with
1612      * {@link VirtualThreadScheduler#current()}.
1613      */
1614     static VirtualThreadScheduler createExternalView(VirtualThreadScheduler delegate) {
1615         return new VirtualThreadScheduler() {
1616             private void check(VirtualThreadTask task) {
1617                 var vthread = (VirtualThread) task.thread();
1618                 VirtualThreadScheduler scheduler = vthread.scheduler;
1619                 if (scheduler != this && scheduler != DEFAULT_SCHEDULER) {
1620                     throw new IllegalArgumentException();
1621                 }
1622             }
1623             @Override
1624             public void onStart(VirtualThreadTask task) {
1625                 check(task);
1626                 delegate.onStart(task);
1627             }
1628             @Override
1629             public void onContinue(VirtualThreadTask task) {
1630                 check(task);
1631                 delegate.onContinue(task);
1632             }
1633             @Override
1634             public String toString() {
1635                 return delegate.toString();
1636             }
1637         };
1638     }
1639 
1640     /**
1641      * Schedule a runnable task to run after a delay.
1642      */
1643     private Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1644         if (USE_STPE) {


1645             return DelayedTaskSchedulers.schedule(command, delay, unit);
1646         } else {
1647             return scheduler.schedule(command, delay, unit);
1648         }
1649     }
1650 
1651     /**
1652      * Supports scheduling a runnable task to run after a delay. It uses a number
1653      * of ScheduledThreadPoolExecutor instances to reduce contention on the delayed
1654      * work queue used. This class is used when using a custom scheduler.
1655      */
1656     static class DelayedTaskSchedulers {
1657         private static final ScheduledExecutorService[] INSTANCE = createDelayedTaskSchedulers();
1658 
1659         static Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1660             long tid = Thread.currentThread().threadId();
1661             int index = (int) tid & (INSTANCE.length - 1);
1662             return INSTANCE[index].schedule(command, delay, unit);
1663         }
1664 
1665         private static ScheduledExecutorService[] createDelayedTaskSchedulers() {
1666             String propName = "jdk.virtualThreadScheduler.timerQueues";
1667             String propValue = System.getProperty(propName);
1668             int queueCount;
1669             if (propValue != null) {
1670                 queueCount = Integer.parseInt(propValue);
1671                 if (queueCount != Integer.highestOneBit(queueCount)) {
1672                     throw new RuntimeException("Value of " + propName + " must be power of 2");
1673                 }
1674             } else {
1675                 int ncpus = Runtime.getRuntime().availableProcessors();
1676                 queueCount = Math.max(Integer.highestOneBit(ncpus / 4), 1);
1677             }
1678             var schedulers = new ScheduledExecutorService[queueCount];
1679             for (int i = 0; i < queueCount; i++) {
1680                 ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor)
1681                     Executors.newScheduledThreadPool(1, task -> {
1682                         Thread t = InnocuousThread.newThread("VirtualThread-unparker", task);
1683                         t.setDaemon(true);
1684                         return t;
1685                     });
1686                 stpe.setRemoveOnCancelPolicy(true);
1687                 schedulers[i] = stpe;
1688             }
1689             return schedulers;
1690         }
1691     }
1692 
1693     /**
1694      * Schedule virtual threads that are ready to be scheduled after they blocked on
1695      * monitor enter.
1696      */
1697     private static void unblockVirtualThreads() {
1698         while (true) {
1699             VirtualThread vthread = takeVirtualThreadListToUnblock();
1700             while (vthread != null) {
1701                 assert vthread.onWaitingList;
1702                 VirtualThread nextThread = vthread.next;
1703 
1704                 // remove from list and unblock
1705                 vthread.next = null;
1706                 boolean changed = vthread.compareAndSetOnWaitingList(true, false);
1707                 assert changed;
1708                 vthread.unblock();
1709 
1710                 vthread = nextThread;
1711             }
1712         }
1713     }
1714 
1715     /**
1716      * Retrieves the list of virtual threads that are waiting to be unblocked, waiting
1717      * if necessary until a list of one or more threads becomes available.
1718      */
1719     private static native VirtualThread takeVirtualThreadListToUnblock();
1720 
1721     static {
1722         var unblocker = InnocuousThread.newThread("VirtualThread-unblocker",
1723                 VirtualThread::unblockVirtualThreads);
1724         unblocker.setDaemon(true);
1725         unblocker.start();
1726     }
1727 }
--- EOF ---