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.Executors;
  33 import java.util.concurrent.ForkJoinPool;

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



 272         }

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













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


















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

 485             try {
 486                 ct.getPool().lazySubmit(ForkJoinTask.adapt(runContinuation));
 487             } catch (RejectedExecutionException ree) {
 488                 submitFailed(ree);
 489                 throw ree;
 490             } catch (OutOfMemoryError e) {
 491                 submitRunContinuation();
 492             }
 493         } else {
 494             submitRunContinuation();
 495         }
 496     }
 497 
 498     /**
 499      * Invoked from a carrier thread to externally submit the runContinuation task to the
 500      * scheduler. If invoked by a thread for a custom scheduler, then it just submits the
 501      * task to the scheduler.
 502      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 503      * @throws RejectedExecutionException
 504      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 505      */
 506     private void externalSubmitRunContinuation() {
 507         assert !currentThread().isVirtual();
 508         if (currentThread() instanceof CarrierThread ct) {
 509             try {
 510                 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
 511             } catch (RejectedExecutionException ree) {
 512                 submitFailed(ree);
 513                 throw ree;
 514             } catch (OutOfMemoryError e) {
 515                 submitRunContinuation();
 516             }
 517         } else {
 518             submitRunContinuation();
 519         }
 520     }
 521 
 522     /**
 523      * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
 524      */
 525     private void submitFailed(RejectedExecutionException ree) {
 526         var event = new VirtualThreadSubmitFailedEvent();
 527         if (event.isEnabled()) {
 528             event.javaThreadId = threadId();
 529             event.exceptionMessage = ree.getMessage();
 530             event.commit();
 531         }
 532     }
 533 
 534     /**
 535      * Runs a task in the context of this virtual thread.
 536      */
 537     private void run(Runnable task) {
 538         assert Thread.currentThread() == this && state == RUNNING;
 539 
 540         // emit JFR event if enabled
 541         if (VirtualThreadStartEvent.isTurnedOn()) {
 542             var event = new VirtualThreadStartEvent();
 543             event.javaThreadId = threadId();
 544             event.commit();
 545         }
 546 
 547         Object bindings = Thread.scopedValueBindings();
 548         try {
 549             runWith(bindings, task);
 550         } catch (Throwable exc) {
 551             dispatchUncaughtException(exc);
 552         } finally {
 553             // pop any remaining scopes from the stack, this may block
 554             StackableScope.popAll();
 555 
 556             // emit JFR event if enabled
 557             if (VirtualThreadEndEvent.isTurnedOn()) {
 558                 var event = new VirtualThreadEndEvent();
 559                 event.javaThreadId = threadId();
 560                 event.commit();
 561             }
 562         }
 563     }
 564 
 565     /**
 566      * Mounts this virtual thread onto the current platform thread. On
 567      * return, the current thread is the virtual thread.
 568      */
 569     @ChangesCurrentThread
 570     @ReservedStackAccess
 571     private void mount() {
 572         startTransition(/*mount*/true);
 573         // We assume following volatile accesses provide equivalent
 574         // of acquire ordering, otherwise we need U.loadFence() here.
 575 
 576         // sets the carrier thread
 577         Thread carrier = Thread.currentCarrierThread();
 578         setCarrierThread(carrier);
 579 
 580         // sync up carrier thread interrupted status if needed
 581         if (interrupted) {
 582             carrier.setInterrupt();
 583         } else if (carrier.isInterrupted()) {
 584             synchronized (interruptLock) {
 585                 // need to recheck interrupted status
 586                 if (!interrupted) {
 587                     carrier.clearInterrupt();
 588                 }
 589             }
 590         }
 591 
 592         // set Thread.currentThread() to return this virtual thread
 593         carrier.setCurrentThread(this);
 594     }
 595 
 596     /**
 597      * Unmounts this virtual thread from the carrier. On return, the
 598      * current thread is the current platform thread.
 599      */
 600     @ChangesCurrentThread
 601     @ReservedStackAccess
 602     private void unmount() {
 603         assert !Thread.holdsLock(interruptLock);
 604 
 605         // set Thread.currentThread() to return the platform thread
 606         Thread carrier = this.carrierThread;
 607         carrier.setCurrentThread(carrier);
 608 
 609         // break connection to carrier thread, synchronized with interrupt
 610         synchronized (interruptLock) {
 611             setCarrierThread(null);
 612         }
 613         carrier.clearInterrupt();
 614 
 615         // We assume previous volatile accesses provide equivalent
 616         // of release ordering, otherwise we need U.storeFence() here.
 617         endTransition(/*mount*/false);
 618     }
 619 
 620     /**
 621      * Invokes Continuation.yield, notifying JVMTI (if enabled) to hide frames until
 622      * the continuation continues.
 623      */
 624     @Hidden
 625     private boolean yieldContinuation() {
 626         startTransition(/*mount*/false);
 627         try {
 628             return Continuation.yield(VTHREAD_SCOPE);
 629         } finally {
 630             endTransition(/*mount*/true);
 631         }
 632     }
 633 
 634     /**
 635      * Invoked in the context of the carrier thread after the Continuation yields when
 636      * parking, blocking on monitor enter, Object.wait, or Thread.yield.
 637      */
 638     private void afterYield() {
 639         assert carrierThread == null;
 640 
 641         // re-adjust parallelism if the virtual thread yielded when compensating
 642         if (currentThread() instanceof CarrierThread ct) {
 643             ct.endBlocking();
 644         }
 645 
 646         int s = state();
 647 
 648         // LockSupport.park/parkNanos
 649         if (s == PARKING || s == TIMED_PARKING) {
 650             int newState;
 651             if (s == PARKING) {
 652                 setState(newState = PARKED);
 653             } else {
 654                 // schedule unpark
 655                 long timeout = this.timeout;
 656                 assert timeout > 0;
 657                 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS);
 658                 setState(newState = TIMED_PARKED);
 659             }
 660 
 661             // may have been unparked while parking
 662             if (parkPermit && compareAndSetState(newState, UNPARKED)) {
 663                 // lazy submit if local queue is empty
 664                 lazySubmitRunContinuation();
 665             }
 666             return;
 667         }
 668 
 669         // Thread.yield
 670         if (s == YIELDING) {
 671             setState(YIELDED);
 672 
 673             // external submit if there are no tasks in the local task queue
 674             if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
 675                 externalSubmitRunContinuation();
 676             } else {
 677                 submitRunContinuation();
 678             }
 679             return;
 680         }
 681 
 682         // blocking on monitorenter
 683         if (s == BLOCKING) {
 684             setState(BLOCKED);
 685 
 686             // may have been unblocked while blocking
 687             if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
 688                 // lazy submit if local queue is empty
 689                 lazySubmitRunContinuation();
 690             }
 691             return;
 692         }
 693 
 694         // Object.wait
 695         if (s == WAITING || s == TIMED_WAITING) {
 696             int newState;
 697             boolean blocked;
 698             boolean interruptible = interruptibleWait;
 699             if (s == WAITING) {
 700                 setState(newState = WAIT);
 701                 // may have been notified while in transition
 702                 blocked = notified && compareAndSetState(WAIT, BLOCKED);
 703             } else {
 704                 // For timed-wait, a timeout task is scheduled to execute. The timeout
 705                 // task will change the thread state to UNBLOCKED and submit the thread
 706                 // to the scheduler. A sequence number is used to ensure that the timeout
 707                 // task only unblocks the thread for this timed-wait. We synchronize with
 708                 // the timeout task to coordinate access to the sequence number and to
 709                 // ensure the timeout task doesn't execute until the thread has got to
 710                 // the TIMED_WAIT state.
 711                 long timeout = this.timeout;
 712                 assert timeout > 0;
 713                 synchronized (timedWaitLock()) {
 714                     byte seqNo = ++timedWaitSeqNo;
 715                     timeoutTask = schedule(() -> waitTimeoutExpired(seqNo), timeout, MILLISECONDS);
 716                     setState(newState = TIMED_WAIT);
 717                     // May have been notified while in transition. This must be done while
 718                     // holding the monitor to avoid changing the state of a new timed wait call.
 719                     blocked = notified && compareAndSetState(TIMED_WAIT, BLOCKED);
 720                 }
 721             }
 722 
 723             if (blocked) {
 724                 // may have been unblocked already
 725                 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
 726                     lazySubmitRunContinuation();
 727                 }
 728             } else {
 729                 // may have been interrupted while in transition to wait state
 730                 if (interruptible && interrupted && compareAndSetState(newState, UNBLOCKED)) {
 731                     lazySubmitRunContinuation();
 732                 }
 733             }
 734             return;
 735         }
 736 
 737         assert false;
 738     }
 739 
 740     /**
 741      * Invoked after the continuation completes.
 742      */
 743     private void afterDone() {
 744         afterDone(true);
 745     }
 746 
 747     /**
 748      * Invoked after the continuation completes (or start failed). Sets the thread
 749      * state to TERMINATED and notifies anyone waiting for the thread to terminate.
 750      *
 751      * @param notifyContainer true if its container should be notified
 752      */
 753     private void afterDone(boolean notifyContainer) {
 754         assert carrierThread == null;
 755         setState(TERMINATED);
 756 
 757         // notifyAll to wakeup any threads waiting for this thread to terminate
 758         if (notifyAllAfterTerminate) {
 759             synchronized (this) {
 760                 notifyAll();
 761             }
 762         }
 763 
 764         // notify container
 765         if (notifyContainer) {
 766             threadContainer().remove(this);
 767         }
 768 
 769         // clear references to thread locals
 770         clearReferences();
 771     }
 772 
 773     /**
 774      * Schedules this {@code VirtualThread} to execute.
 775      *
 776      * @throws IllegalStateException if the container is shutdown or closed
 777      * @throws IllegalThreadStateException if the thread has already been started
 778      * @throws RejectedExecutionException if the scheduler cannot accept a task
 779      */
 780     private void start(ThreadContainer container, boolean lazy) {

 781         if (!compareAndSetState(NEW, STARTED)) {
 782             throw new IllegalThreadStateException("Already started");
 783         }
 784 
 785         // bind thread to container
 786         assert threadContainer() == null;
 787         setThreadContainer(container);
 788 
 789         // start thread
 790         boolean addedToContainer = false;
 791         boolean started = false;
 792         try {
 793             container.add(this);  // may throw
 794             addedToContainer = true;
 795 
 796             // scoped values may be inherited
 797             inheritScopedValueBindings(container);
 798 
 799             // submit task to schedule
 800             try {
 801                 if (currentThread().isVirtual()) {
 802                     Continuation.pin();
 803                     try {
 804                         if (scheduler == BUILTIN_SCHEDULER
 805                                 && currentCarrierThread() instanceof CarrierThread ct) {
 806                             ForkJoinPool pool = ct.getPool();
 807                             ForkJoinTask<?> task = ForkJoinTask.adapt(runContinuation);
 808                             if (lazy) {
 809                                 pool.lazySubmit(task);
 810                             } else {
 811                                 pool.externalSubmit(task);
 812                             }
 813                         } else {
 814                             scheduler.onStart(runContinuation);
 815                         }
 816                     } finally {
 817                         Continuation.unpin();
 818                     }
 819                 } else {
 820                     scheduler.onStart(runContinuation);
 821                 }
 822             } catch (RejectedExecutionException ree) {
 823                 submitFailed(ree);
 824                 throw ree;
 825             }
 826 
 827             started = true;
 828         } finally {
 829             if (!started) {
 830                 afterDone(addedToContainer);
 831             }
 832         }
 833     }
 834 
 835     @Override
 836     void start(ThreadContainer container) {
 837         start(container, false);
 838     }
 839 
 840     @Override
 841     public void start() {
 842         start(ThreadContainers.root(), false);
 843     }
 844 
 845     /**
 846      * Schedules this thread to begin execution without guarantee that it will execute.
 847      */
 848     void lazyStart() {
 849         start(ThreadContainers.root(), true);
 850     }
 851 
 852     @Override
 853     public void run() {
 854         // do nothing
 855     }
 856 
 857     /**
 858      * Invoked by Thread.join before a thread waits for this virtual thread to terminate.
 859      */
 860     void beforeJoin() {
 861         notifyAllAfterTerminate = true;
 862     }
 863 
 864     /**
 865      * Parks until unparked or interrupted. If already unparked then the parking
 866      * permit is consumed and this method completes immediately (meaning it doesn't
 867      * yield). It also completes immediately if the interrupted status is set.
 868      */
 869     @Override
 870     void park() {
 871         assert Thread.currentThread() == this;
 872 
 873         // complete immediately if parking permit available or interrupted
 874         if (getAndSetParkPermit(false) || interrupted)
 875             return;
 876 
 877         // park the thread
 878         boolean yielded = false;
 879         setState(PARKING);
 880         try {
 881             yielded = yieldContinuation();
 882         } catch (OutOfMemoryError e) {
 883             // park on carrier
 884         } finally {
 885             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 886             if (!yielded) {
 887                 assert state() == PARKING;
 888                 setState(RUNNING);
 889             }
 890         }
 891 
 892         // park on the carrier thread when pinned
 893         if (!yielded) {
 894             parkOnCarrierThread(false, 0);
 895         }
 896     }
 897 
 898     /**
 899      * Parks up to the given waiting time or until unparked or interrupted.
 900      * If already unparked then the parking permit is consumed and this method
 901      * completes immediately (meaning it doesn't yield). It also completes immediately
 902      * if the interrupted status is set or the waiting time is {@code <= 0}.
 903      *
 904      * @param nanos the maximum number of nanoseconds to wait.
 905      */
 906     @Override
 907     void parkNanos(long nanos) {
 908         assert Thread.currentThread() == this;
 909 
 910         // complete immediately if parking permit available or interrupted
 911         if (getAndSetParkPermit(false) || interrupted)
 912             return;
 913 
 914         // park the thread for the waiting time
 915         if (nanos > 0) {
 916             long startTime = System.nanoTime();
 917 
 918             // park the thread, afterYield will schedule the thread to unpark
 919             boolean yielded = false;
 920             timeout = nanos;
 921             setState(TIMED_PARKING);
 922             try {
 923                 yielded = yieldContinuation();
 924             } catch (OutOfMemoryError e) {
 925                 // park on carrier
 926             } finally {
 927                 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 928                 if (!yielded) {
 929                     assert state() == TIMED_PARKING;
 930                     setState(RUNNING);
 931                 }
 932             }
 933 
 934             // park on carrier thread for remaining time when pinned (or OOME)
 935             if (!yielded) {
 936                 long remainingNanos = nanos - (System.nanoTime() - startTime);
 937                 parkOnCarrierThread(true, remainingNanos);
 938             }
 939         }
 940     }
 941 
 942     /**
 943      * Parks the current carrier thread up to the given waiting time or until
 944      * unparked or interrupted. If the virtual thread is interrupted then the
 945      * interrupted status will be propagated to the carrier thread.
 946      * @param timed true for a timed park, false for untimed
 947      * @param nanos the waiting time in nanoseconds
 948      */
 949     private void parkOnCarrierThread(boolean timed, long nanos) {
 950         assert state() == RUNNING;
 951 
 952         setState(timed ? TIMED_PINNED : PINNED);
 953         try {
 954             if (!parkPermit) {
 955                 if (!timed) {
 956                     U.park(false, 0);
 957                 } else if (nanos > 0) {
 958                     U.park(false, nanos);
 959                 }
 960             }
 961         } finally {
 962             setState(RUNNING);
 963         }
 964 
 965         // consume parking permit
 966         setParkPermit(false);
 967 
 968         // JFR jdk.VirtualThreadPinned event
 969         postPinnedEvent("LockSupport.park");
 970     }
 971 
 972     /**
 973      * Call into VM when pinned to record a JFR jdk.VirtualThreadPinned event.
 974      * Recording the event in the VM avoids having JFR event recorded in Java
 975      * with the same name, but different ID, to events recorded by the VM.
 976      */
 977     @Hidden
 978     private static native void postPinnedEvent(String op);
 979 
 980     /**
 981      * Re-enables this virtual thread for scheduling. If this virtual thread is parked
 982      * then its task is scheduled to continue, otherwise its next call to {@code park} or
 983      * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block.
 984      * @param lazySubmit to use lazySubmit if possible
 985      * @throws RejectedExecutionException if the scheduler cannot accept a task
 986      */
 987     private void unpark(boolean lazySubmit) {
 988         if (!getAndSetParkPermit(true) && currentThread() != this) {
 989             int s = state();
 990 
 991             // unparked while parked
 992             if ((s == PARKED || s == TIMED_PARKED) && compareAndSetState(s, UNPARKED)) {
 993 
 994                 if (lazySubmit && currentThread().isVirtual()) {
 995                     Continuation.pin();
 996                     try {
 997                         if (scheduler == BUILTIN_SCHEDULER
 998                                 && currentCarrierThread() instanceof CarrierThread ct) {
 999                             ct.getPool().lazySubmit(ForkJoinTask.adapt(runContinuation));
1000                             return;
1001                         }
1002                     } catch (RejectedExecutionException ree) {
1003                         submitFailed(ree);
1004                         throw ree;
1005                     } catch (OutOfMemoryError e) {
1006                         // fall-though
1007                     } finally {
1008                         Continuation.unpin();
1009                     }
1010                 }
1011 
1012                 submitRunContinuation();
1013                 return;
1014             }
1015 
1016             // unparked while parked when pinned
1017             if (s == PINNED || s == TIMED_PINNED) {
1018                 // unpark carrier thread when pinned
1019                 disableSuspendAndPreempt();
1020                 try {
1021                     synchronized (carrierThreadAccessLock()) {
1022                         Thread carrier = carrierThread;
1023                         if (carrier != null && ((s = state()) == PINNED || s == TIMED_PINNED)) {
1024                             U.unpark(carrier);
1025                         }
1026                     }
1027                 } finally {
1028                     enableSuspendAndPreempt();
1029                 }
1030                 return;
1031             }
1032         }
1033     }
1034 
1035     @Override
1036     void unpark() {
1037         unpark(false);
1038     }
1039 
1040     @Override
1041     void lazyUnpark() {
1042         unpark(true);
1043     }
1044 
1045     /**
1046      * Invoked by unblocker thread to unblock this virtual thread.
1047      */
1048     private void unblock() {
1049         assert !Thread.currentThread().isVirtual();
1050         blockPermit = true;
1051         if (state() == BLOCKED && compareAndSetState(BLOCKED, UNBLOCKED)) {
1052             submitRunContinuation();
1053         }
1054     }
1055 
1056     /**
1057      * Invoked by FJP worker thread or STPE thread when park timeout expires.
1058      */
1059     private void parkTimeoutExpired() {
1060         assert !VirtualThread.currentThread().isVirtual();
1061         unpark(true);
1062     }
1063 
1064     /**
1065      * Invoked by FJP worker thread or STPE thread when wait timeout expires.
1066      * If the virtual thread is in timed-wait then this method will unblock the thread
1067      * and submit its task so that it continues and attempts to reenter the monitor.
1068      * This method does nothing if the thread has been woken by notify or interrupt.
1069      */
1070     private void waitTimeoutExpired(byte seqNo) {
1071         assert !Thread.currentThread().isVirtual();
1072 
1073         synchronized (timedWaitLock()) {
1074             if (seqNo != timedWaitSeqNo) {
1075                 // this timeout task is for a past timed-wait
1076                 return;
1077             }
1078             if (!compareAndSetState(TIMED_WAIT, UNBLOCKED)) {
1079                 // already notified (or interrupted)
1080                 return;
1081             }
1082         }
1083 
1084         lazySubmitRunContinuation();
1085     }
1086 
1087     /**
1088      * Attempts to yield the current virtual thread (Thread.yield).
1089      */
1090     void tryYield() {
1091         assert Thread.currentThread() == this;
1092         setState(YIELDING);
1093         boolean yielded = false;
1094         try {
1095             yielded = yieldContinuation();  // may throw
1096         } finally {
1097             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
1098             if (!yielded) {
1099                 assert state() == YIELDING;
1100                 setState(RUNNING);
1101             }
1102         }
1103     }
1104 
1105     /**
1106      * Sleep the current thread for the given sleep time (in nanoseconds). If
1107      * nanos is 0 then the thread will attempt to yield.
1108      *
1109      * @implNote This implementation parks the thread for the given sleeping time
1110      * and will therefore be observed in PARKED state during the sleep. Parking
1111      * will consume the parking permit so this method makes available the parking
1112      * permit after the sleep. This may be observed as a spurious, but benign,
1113      * wakeup when the thread subsequently attempts to park.
1114      *
1115      * @param nanos the maximum number of nanoseconds to sleep
1116      * @throws InterruptedException if interrupted while sleeping
1117      */
1118     void sleepNanos(long nanos) throws InterruptedException {
1119         assert Thread.currentThread() == this && nanos >= 0;
1120         if (getAndClearInterrupt())
1121             throw new InterruptedException();
1122         if (nanos == 0) {
1123             tryYield();
1124         } else {
1125             // park for the sleep time
1126             try {
1127                 long remainingNanos = nanos;
1128                 long startNanos = System.nanoTime();
1129                 while (remainingNanos > 0) {
1130                     parkNanos(remainingNanos);
1131                     if (getAndClearInterrupt()) {
1132                         throw new InterruptedException();
1133                     }
1134                     remainingNanos = nanos - (System.nanoTime() - startNanos);
1135                 }
1136             } finally {
1137                 // may have been unparked while sleeping
1138                 setParkPermit(true);
1139             }
1140         }
1141     }
1142 
1143     @Override
1144     void blockedOn(Interruptible b) {
1145         disableSuspendAndPreempt();
1146         try {
1147             super.blockedOn(b);
1148         } finally {
1149             enableSuspendAndPreempt();
1150         }
1151     }
1152 
1153     @Override
1154     public void interrupt() {
1155         if (Thread.currentThread() != this) {
1156             // if current thread is a virtual thread then prevent it from being
1157             // suspended or unmounted when entering or holding interruptLock
1158             Interruptible blocker;
1159             disableSuspendAndPreempt();
1160             try {
1161                 synchronized (interruptLock) {
1162                     interrupted = true;
1163                     blocker = nioBlocker();
1164                     if (blocker != null) {
1165                         blocker.interrupt(this);
1166                     }
1167 
1168                     // interrupt carrier thread if mounted
1169                     Thread carrier = carrierThread;
1170                     if (carrier != null) carrier.setInterrupt();
1171                 }
1172             } finally {
1173                 enableSuspendAndPreempt();
1174             }
1175 
1176             // notify blocker after releasing interruptLock
1177             if (blocker != null) {
1178                 blocker.postInterrupt();
1179             }
1180 
1181             // make available parking permit, unpark thread if parked
1182             unpark();
1183 
1184             // if thread is waiting in Object.wait then schedule to try to reenter
1185             int s = state();
1186             if ((s == WAIT || s == TIMED_WAIT) && compareAndSetState(s, UNBLOCKED)) {
1187                 submitRunContinuation();
1188             }
1189 
1190         } else {
1191             interrupted = true;
1192             carrierThread.setInterrupt();
1193             setParkPermit(true);
1194         }
1195     }
1196 
1197     @Override
1198     public boolean isInterrupted() {
1199         return interrupted;
1200     }
1201 
1202     @Override
1203     boolean getAndClearInterrupt() {
1204         assert Thread.currentThread() == this;
1205         boolean oldValue = interrupted;
1206         if (oldValue) {
1207             disableSuspendAndPreempt();
1208             try {
1209                 synchronized (interruptLock) {
1210                     interrupted = false;
1211                     carrierThread.clearInterrupt();
1212                 }
1213             } finally {
1214                 enableSuspendAndPreempt();
1215             }
1216         }
1217         return oldValue;
1218     }
1219 
1220     @Override
1221     Thread.State threadState() {
1222         switch (state()) {
1223             case NEW:
1224                 return Thread.State.NEW;
1225             case STARTED:
1226                 // return NEW if thread container not yet set
1227                 if (threadContainer() == null) {
1228                     return Thread.State.NEW;
1229                 } else {
1230                     return Thread.State.RUNNABLE;
1231                 }
1232             case UNPARKED:
1233             case UNBLOCKED:
1234             case YIELDED:
1235                 // runnable, not mounted
1236                 return Thread.State.RUNNABLE;
1237             case RUNNING:
1238                 // if mounted then return state of carrier thread
1239                 if (Thread.currentThread() != this) {
1240                     disableSuspendAndPreempt();
1241                     try {
1242                         synchronized (carrierThreadAccessLock()) {
1243                             Thread carrierThread = this.carrierThread;
1244                             if (carrierThread != null) {
1245                                 return carrierThread.threadState();
1246                             }
1247                         }
1248                     } finally {
1249                         enableSuspendAndPreempt();
1250                     }
1251                 }
1252                 // runnable, mounted
1253                 return Thread.State.RUNNABLE;
1254             case PARKING:
1255             case TIMED_PARKING:
1256             case WAITING:
1257             case TIMED_WAITING:
1258             case YIELDING:
1259                 // runnable, in transition
1260                 return Thread.State.RUNNABLE;
1261             case PARKED:
1262             case PINNED:
1263             case WAIT:
1264                 return Thread.State.WAITING;
1265             case TIMED_PARKED:
1266             case TIMED_PINNED:
1267             case TIMED_WAIT:
1268                 return Thread.State.TIMED_WAITING;
1269             case BLOCKING:
1270             case BLOCKED:
1271                 return Thread.State.BLOCKED;
1272             case TERMINATED:
1273                 return Thread.State.TERMINATED;
1274             default:
1275                 throw new InternalError();
1276         }
1277     }
1278 
1279     @Override
1280     boolean alive() {
1281         int s = state;
1282         return (s != NEW && s != TERMINATED);
1283     }
1284 
1285     @Override
1286     boolean isTerminated() {
1287         return (state == TERMINATED);
1288     }
1289 
1290     @Override
1291     public String toString() {
1292         StringBuilder sb = new StringBuilder("VirtualThread[#");
1293         sb.append(threadId());
1294         String name = getName();
1295         if (!name.isEmpty()) {
1296             sb.append(",");
1297             sb.append(name);
1298         }
1299         sb.append("]/");
1300 
1301         // add the carrier state and thread name when mounted
1302         boolean mounted;
1303         if (Thread.currentThread() == this) {
1304             mounted = appendCarrierInfo(sb);
1305         } else {
1306             disableSuspendAndPreempt();
1307             try {
1308                 synchronized (carrierThreadAccessLock()) {
1309                     mounted = appendCarrierInfo(sb);
1310                 }
1311             } finally {
1312                 enableSuspendAndPreempt();
1313             }
1314         }
1315 
1316         // add virtual thread state when not mounted
1317         if (!mounted) {
1318             String stateAsString = threadState().toString();
1319             sb.append(stateAsString.toLowerCase(Locale.ROOT));
1320         }
1321 
1322         return sb.toString();
1323     }
1324 
1325     /**
1326      * Appends the carrier state and thread name to the string buffer if mounted.
1327      * @return true if mounted, false if not mounted
1328      */
1329     private boolean appendCarrierInfo(StringBuilder sb) {
1330         assert Thread.currentThread() == this || Thread.holdsLock(carrierThreadAccessLock());
1331         Thread carrier = carrierThread;
1332         if (carrier != null) {
1333             String stateAsString = carrier.threadState().toString();
1334             sb.append(stateAsString.toLowerCase(Locale.ROOT));
1335             sb.append('@');
1336             sb.append(carrier.getName());
1337             return true;
1338         } else {
1339             return false;
1340         }
1341     }
1342 
1343     @Override
1344     public int hashCode() {
1345         return (int) threadId();
1346     }
1347 
1348     @Override
1349     public boolean equals(Object obj) {
1350         return obj == this;
1351     }
1352 
1353     /**
1354      * Returns the lock object to synchronize on when accessing carrierThread.
1355      * The lock prevents carrierThread from being reset to null during unmount.
1356      */
1357     private Object carrierThreadAccessLock() {
1358         // return interruptLock as unmount has to coordinate with interrupt
1359         return interruptLock;
1360     }
1361 
1362     /**
1363      * Returns a lock object for coordinating timed-wait setup and timeout handling.
1364      */
1365     private Object timedWaitLock() {
1366         // use this object for now to avoid the overhead of introducing another lock
1367         return runContinuation;
1368     }
1369 
1370     /**
1371      * Disallow the current thread be suspended or preempted.
1372      */
1373     private void disableSuspendAndPreempt() {
1374         notifyJvmtiDisableSuspend(true);
1375         Continuation.pin();
1376     }
1377 
1378     /**
1379      * Allow the current thread be suspended or preempted.
1380      */
1381     private void enableSuspendAndPreempt() {
1382         Continuation.unpin();
1383         notifyJvmtiDisableSuspend(false);
1384     }
1385 
1386     // -- wrappers for get/set of state, parking permit, and carrier thread --
1387 
1388     private int state() {
1389         return state;  // volatile read
1390     }
1391 
1392     private void setState(int newValue) {
1393         state = newValue;  // volatile write
1394     }
1395 
1396     private boolean compareAndSetState(int expectedValue, int newValue) {
1397         return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1398     }
1399 
1400     private boolean compareAndSetOnWaitingList(boolean expectedValue, boolean newValue) {
1401         return U.compareAndSetBoolean(this, ON_WAITING_LIST, expectedValue, newValue);
1402     }
1403 
1404     private void setParkPermit(boolean newValue) {
1405         if (parkPermit != newValue) {
1406             parkPermit = newValue;
1407         }
1408     }
1409 
1410     private boolean getAndSetParkPermit(boolean newValue) {
1411         if (parkPermit != newValue) {
1412             return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1413         } else {
1414             return newValue;
1415         }
1416     }
1417 
1418     private void setCarrierThread(Thread carrier) {
1419         // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1420         this.carrierThread = carrier;
1421     }
1422 
1423     // The following four methods notify the VM when a "transition" starts and ends.
1424     // A "mount transition" embodies the steps to transfer control from a platform
1425     // thread to a virtual thread, changing the thread identity, and starting or
1426     // resuming the virtual thread's continuation on the carrier.
1427     // An "unmount transition" embodies the steps to transfer control from a virtual
1428     // thread to its carrier, suspending the virtual thread's continuation, and
1429     // restoring the thread identity to the platform thread.
1430     // The notifications to the VM are necessary in order to coordinate with functions
1431     // (JVMTI mostly) that disable transitions for one or all virtual threads. Starting
1432     // a transition may block if transitions are disabled. Ending a transition may
1433     // notify a thread that is waiting to disable transitions. The notifications are
1434     // also used to post JVMTI events for virtual thread start and end.
1435 
1436     @IntrinsicCandidate
1437     @JvmtiMountTransition
1438     private native void endFirstTransition();
1439 
1440     @IntrinsicCandidate
1441     @JvmtiMountTransition
1442     private native void startFinalTransition();
1443 
1444     @IntrinsicCandidate
1445     @JvmtiMountTransition
1446     private native void startTransition(boolean mount);
1447 
1448     @IntrinsicCandidate
1449     @JvmtiMountTransition
1450     private native void endTransition(boolean mount);
1451 
1452     @IntrinsicCandidate
1453     private static native void notifyJvmtiDisableSuspend(boolean enter);
1454 
1455     private static native void registerNatives();
1456     static {
1457         registerNatives();
1458 
1459         // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1460         var group = Thread.virtualThreadGroup();
1461     }
1462 
1463     /**
1464      * Loads a VirtualThreadScheduler with the given class name. The class must be public
1465      * in an exported package, with public one-arg or no-arg constructor, and be visible
1466      * to the system class loader.
1467      * @param delegate the scheduler that the custom scheduler may delegate to
1468      * @param cn the class name of the custom scheduler
1469      */
1470     private static VirtualThreadScheduler loadCustomScheduler(VirtualThreadScheduler delegate, String cn) {
1471         VirtualThreadScheduler scheduler;
1472         try {
1473             Class<?> clazz = Class.forName(cn, true, ClassLoader.getSystemClassLoader());
1474             // 1-arg constructor
1475             try {
1476                 Constructor<?> ctor = clazz.getConstructor(VirtualThreadScheduler.class);
1477                 return (VirtualThreadScheduler) ctor.newInstance(delegate);
1478             } catch (NoSuchMethodException e) {
1479                 // 0-arg constructor
1480                 Constructor<?> ctor = clazz.getConstructor();
1481                 scheduler = (VirtualThreadScheduler) ctor.newInstance();
1482             }
1483         } catch (Exception ex) {
1484             throw new Error(ex);
1485         }
1486         System.err.println("WARNING: Using custom default scheduler, this is an experimental feature!");
1487         return scheduler;
1488     }
1489 
1490     /**
1491      * Creates the built-in ForkJoinPool scheduler.
1492      * @param wrapped true if wrapped by a custom default scheduler
1493      */
1494     private static VirtualThreadScheduler createBuiltinScheduler(boolean wrapped) {

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


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