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



 269         }

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













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


















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

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

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


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