< prev index next >

src/java.base/share/classes/java/lang/VirtualThread.java

Print this page

  69     private static final Unsafe U = Unsafe.getUnsafe();
  70     private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
  71     private static final ForkJoinPool DEFAULT_SCHEDULER = createDefaultScheduler();
  72     private static final ScheduledExecutorService UNPARKER = createDelayedTaskScheduler();
  73     private static final int TRACE_PINNING_MODE = tracePinningMode();
  74 
  75     private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
  76     private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
  77     private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
  78     private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
  79 
  80     // scheduler and continuation
  81     private final Executor scheduler;
  82     private final Continuation cont;
  83     private final Runnable runContinuation;
  84 
  85     // virtual thread state, accessed by VM
  86     private volatile int state;
  87 
  88     /*
  89      * Virtual thread state and transitions:
  90      *
  91      *      NEW -> STARTED         // Thread.start
  92      *  STARTED -> TERMINATED      // failed to start
  93      *  STARTED -> RUNNING         // first run

  94      *
  95      *  RUNNING -> PARKING         // Thread attempts to park
  96      *  PARKING -> PARKED          // cont.yield successful, thread is parked
  97      *  PARKING -> PINNED          // cont.yield failed, thread is pinned
  98      *
  99      *   PARKED -> RUNNABLE        // unpark or interrupted
 100      *   PINNED -> RUNNABLE        // unpark or interrupted
 101      *
 102      * RUNNABLE -> RUNNING         // continue execution




 103      *
 104      *  RUNNING -> YIELDING        // Thread.yield
 105      * YIELDING -> RUNNABLE        // yield successful
 106      * YIELDING -> RUNNING         // yield failed
 107      *
 108      *  RUNNING -> TERMINATED      // done
 109      */
 110     private static final int NEW      = 0;
 111     private static final int STARTED  = 1;
 112     private static final int RUNNABLE = 2;     // runnable-unmounted
 113     private static final int RUNNING  = 3;     // runnable-mounted
 114     private static final int PARKING  = 4;
 115     private static final int PARKED   = 5;     // unmounted
 116     private static final int PINNED   = 6;     // mounted
 117     private static final int YIELDING = 7;     // Thread.yield









 118     private static final int TERMINATED = 99;  // final state
 119 
 120     // can be suspended from scheduling when unmounted
 121     private static final int SUSPENDED = 1 << 8;
 122     private static final int RUNNABLE_SUSPENDED = (RUNNABLE | SUSPENDED);
 123     private static final int PARKED_SUSPENDED   = (PARKED | SUSPENDED);
 124 
 125     // parking permit
 126     private volatile boolean parkPermit;
 127 
 128     // carrier thread when mounted, accessed by VM
 129     private volatile Thread carrierThread;
 130 
 131     // termination object when joining, created lazily if needed
 132     private volatile CountDownLatch termination;
 133 
 134     /**
 135      * Returns the continuation scope used for virtual threads.
 136      */
 137     static ContinuationScope continuationScope() {
 138         return VTHREAD_SCOPE;
 139     }
 140 
 141     /**
 142      * Creates a new {@code VirtualThread} to run the given task with the given
 143      * scheduler. If the given scheduler is {@code null} and the current thread

 163                 scheduler = DEFAULT_SCHEDULER;
 164             }
 165         }
 166 
 167         this.scheduler = scheduler;
 168         this.cont = new VThreadContinuation(this, task);
 169         this.runContinuation = this::runContinuation;
 170     }
 171 
 172     /**
 173      * The continuation that a virtual thread executes.
 174      */
 175     private static class VThreadContinuation extends Continuation {
 176         VThreadContinuation(VirtualThread vthread, Runnable task) {
 177             super(VTHREAD_SCOPE, wrap(vthread, task));
 178         }
 179         @Override
 180         protected void onPinned(Continuation.Pinned reason) {
 181             if (TRACE_PINNING_MODE > 0) {
 182                 boolean printAll = (TRACE_PINNING_MODE == 1);
 183                 PinnedThreadPrinter.printStackTrace(System.out, printAll);








 184             }
 185         }
 186         private static Runnable wrap(VirtualThread vthread, Runnable task) {
 187             return new Runnable() {
 188                 @Hidden
 189                 public void run() {
 190                     vthread.run(task);
 191                 }
 192             };
 193         }
 194     }
 195 
 196     /**
 197      * Runs or continues execution of the continuation on the current thread.


 198      */

 199     private void runContinuation() {
 200         // the carrier must be a platform thread
 201         if (Thread.currentThread().isVirtual()) {
 202             throw new WrongThreadException();
 203         }
 204 
 205         // set state to RUNNING
 206         int initialState = state();
 207         if (initialState == STARTED && compareAndSetState(STARTED, RUNNING)) {
 208             // first run
 209         } else if (initialState == RUNNABLE && compareAndSetState(RUNNABLE, RUNNING)) {
 210             // consume parking permit
 211             setParkPermit(false);




 212         } else {
 213             // not runnable
 214             return;
 215         }
 216 
 217         // notify JVMTI before mount
 218         notifyJvmtiMount(/*hide*/true);
 219 
 220         try {
 221             cont.run();
 222         } finally {

 223             if (cont.isDone()) {
 224                 afterTerminate();
 225             } else {
 226                 afterYield();
 227             }
 228         }
 229     }
 230 
 231     /**
 232      * Submits the runContinuation task to the scheduler. For the default scheduler,
 233      * and calling it on a worker thread, the task will be pushed to the local queue,
 234      * otherwise it will be pushed to a submission queue.
 235      *
 236      * @throws RejectedExecutionException
 237      */
 238     private void submitRunContinuation() {
 239         try {
 240             scheduler.execute(runContinuation);
 241         } catch (RejectedExecutionException ree) {
 242             submitFailed(ree);
 243             throw ree;
 244         }
 245     }
 246 
 247     /**
 248      * Submits the runContinuation task to the scheduler with a lazy submit.
 249      * @throws RejectedExecutionException
 250      * @see ForkJoinPool#lazySubmit(ForkJoinTask)
 251      */
 252     private void lazySubmitRunContinuation(ForkJoinPool pool) {
 253         try {
 254             pool.lazySubmit(ForkJoinTask.adapt(runContinuation));
 255         } catch (RejectedExecutionException ree) {
 256             submitFailed(ree);
 257             throw ree;
 258         }
 259     }
 260 
 261     /**
 262      * Submits the runContinuation task to the scheduler as an external submit.
 263      * @throws RejectedExecutionException
 264      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 265      */
 266     private void externalSubmitRunContinuation(ForkJoinPool pool) {
 267         try {
 268             pool.externalSubmit(ForkJoinTask.adapt(runContinuation));
 269         } catch (RejectedExecutionException ree) {
 270             submitFailed(ree);
 271             throw ree;
 272         }
 273     }
 274 
 275     /**
 276      * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
 277      */
 278     private void submitFailed(RejectedExecutionException ree) {
 279         var event = new VirtualThreadSubmitFailedEvent();
 280         if (event.isEnabled()) {
 281             event.javaThreadId = threadId();
 282             event.exceptionMessage = ree.getMessage();
 283             event.commit();
 284         }
 285     }
 286 
 287     /**
 288      * Runs a task in the context of this virtual thread. The virtual thread is
 289      * mounted on the current (carrier) thread before the task runs. It unmounts
 290      * from its carrier thread when the task completes.
 291      */
 292     @ChangesCurrentThread
 293     private void run(Runnable task) {
 294         assert state == RUNNING;
 295 
 296         // first mount
 297         mount();
 298         notifyJvmtiStart();
 299 
 300         // emit JFR event if enabled
 301         if (VirtualThreadStartEvent.isTurnedOn()) {
 302             var event = new VirtualThreadStartEvent();
 303             event.javaThreadId = threadId();
 304             event.commit();
 305         }
 306 
 307         Object bindings = Thread.scopedValueBindings();
 308         try {
 309             runWith(bindings, task);
 310         } catch (Throwable exc) {
 311             dispatchUncaughtException(exc);
 312         } finally {
 313             try {
 314                 // pop any remaining scopes from the stack, this may block
 315                 StackableScope.popAll();
 316 
 317                 // emit JFR event if enabled
 318                 if (VirtualThreadEndEvent.isTurnedOn()) {
 319                     var event = new VirtualThreadEndEvent();
 320                     event.javaThreadId = threadId();
 321                     event.commit();
 322                 }
 323 
 324             } finally {
 325                 // last unmount
 326                 notifyJvmtiEnd();
 327                 unmount();
 328 
 329                 // final state
 330                 setState(TERMINATED);
 331             }
 332         }
 333     }
 334 
 335     /**
 336      * Mounts this virtual thread onto the current platform thread. On
 337      * return, the current thread is the virtual thread.
 338      */
 339     @ChangesCurrentThread
 340     @ReservedStackAccess
 341     private void mount() {



 342         // sets the carrier thread
 343         Thread carrier = Thread.currentCarrierThread();
 344         setCarrierThread(carrier);
 345 
 346         // sync up carrier thread interrupt status if needed
 347         if (interrupted) {
 348             carrier.setInterrupt();
 349         } else if (carrier.isInterrupted()) {
 350             synchronized (interruptLock) {
 351                 // need to recheck interrupt status
 352                 if (!interrupted) {
 353                     carrier.clearInterrupt();
 354                 }
 355             }
 356         }
 357 
 358         // set Thread.currentThread() to return this virtual thread
 359         carrier.setCurrentThread(this);
 360     }
 361 
 362     /**
 363      * Unmounts this virtual thread from the carrier. On return, the
 364      * current thread is the current platform thread.
 365      */
 366     @ChangesCurrentThread
 367     @ReservedStackAccess
 368     private void unmount() {
 369         // set Thread.currentThread() to return the platform thread
 370         Thread carrier = this.carrierThread;
 371         carrier.setCurrentThread(carrier);
 372 
 373         // break connection to carrier thread, synchronized with interrupt
 374         synchronized (interruptLock) {
 375             setCarrierThread(null);
 376         }
 377         carrier.clearInterrupt();



 378     }
 379 
 380     /**
 381      * Sets the current thread to the current carrier thread.
 382      */
 383     @ChangesCurrentThread
 384     @JvmtiMountTransition
 385     private void switchToCarrierThread() {
 386         notifyJvmtiHideFrames(true);
 387         Thread carrier = this.carrierThread;
 388         assert Thread.currentThread() == this
 389                 && carrier == Thread.currentCarrierThread();
 390         carrier.setCurrentThread(carrier);
 391     }
 392 
 393     /**
 394      * Sets the current thread to the given virtual thread.
 395      */
 396     @ChangesCurrentThread
 397     @JvmtiMountTransition

 400         assert carrier == Thread.currentCarrierThread();
 401         carrier.setCurrentThread(vthread);
 402         notifyJvmtiHideFrames(false);
 403     }
 404 
 405     /**
 406      * Executes the given value returning task on the current carrier thread.
 407      */
 408     @ChangesCurrentThread
 409     <V> V executeOnCarrierThread(Callable<V> task) throws Exception {
 410         assert Thread.currentThread() == this;
 411         switchToCarrierThread();
 412         try {
 413             return task.call();
 414         } finally {
 415             switchToVirtualThread(this);
 416         }
 417      }
 418 
 419     /**
 420      * Unmounts this virtual thread, invokes Continuation.yield, and re-mounts the
 421      * thread when continued. When enabled, JVMTI must be notified from this method.
 422      * @return true if the yield was successful
 423      */
 424     @Hidden
 425     @ChangesCurrentThread
 426     private boolean yieldContinuation() {
 427         // unmount
 428         notifyJvmtiUnmount(/*hide*/true);
 429         unmount();
 430         try {
 431             return Continuation.yield(VTHREAD_SCOPE);
 432         } finally {
 433             // re-mount
 434             mount();
 435             notifyJvmtiMount(/*hide*/false);
 436         }
 437     }
 438 
 439     /**
 440      * Invoked after the continuation yields. If parking then it sets the state
 441      * and also re-submits the task to continue if unparked while parking.
 442      * If yielding due to Thread.yield then it just submits the task to continue.
 443      */
 444     private void afterYield() {
 445         int s = state();
 446         assert (s == PARKING || s == YIELDING) && (carrierThread == null);
 447 
 448         if (s == PARKING) {
 449             setState(PARKED);
 450 
 451             // notify JVMTI that unmount has completed, thread is parked
 452             notifyJvmtiUnmount(/*hide*/false);


 453 
 454             // may have been unparked while parking
 455             if (parkPermit && compareAndSetState(PARKED, RUNNABLE)) {
 456                 // lazy submit to continue on the current thread as carrier if possible
 457                 if (currentThread() instanceof CarrierThread ct) {
 458                     lazySubmitRunContinuation(ct.getPool());
 459                 } else {
 460                     submitRunContinuation();
 461                 }
 462 
 463             }
 464         } else if (s == YIELDING) {   // Thread.yield
 465             setState(RUNNABLE);
 466 
 467             // notify JVMTI that unmount has completed, thread is runnable
 468             notifyJvmtiUnmount(/*hide*/false);

 469 
 470             // external submit if there are no tasks in the local task queue
 471             if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
 472                 externalSubmitRunContinuation(ct.getPool());
 473             } else {
 474                 submitRunContinuation();
 475             }

 476         }


 477     }
 478 
 479     /**
 480      * Invoked after the thread terminates execution. It notifies anyone
 481      * waiting for the thread to terminate.
 482      */
 483     private void afterTerminate() {
 484         afterTerminate(true, true);
 485     }
 486 
 487     /**
 488      * Invoked after the thread terminates (or start failed). This method
 489      * notifies anyone waiting for the thread to terminate.
 490      *
 491      * @param notifyContainer true if its container should be notified
 492      * @param executed true if the thread executed, false if it failed to start
 493      */
 494     private void afterTerminate(boolean notifyContainer, boolean executed) {
 495         assert (state() == TERMINATED) && (carrierThread == null);
 496 
 497         if (executed) {
 498             notifyJvmtiUnmount(/*hide*/false);
 499         }
 500 
 501         // notify anyone waiting for this virtual thread to terminate
 502         CountDownLatch termination = this.termination;
 503         if (termination != null) {
 504             assert termination.getCount() == 1;
 505             termination.countDown();
 506         }
 507 
 508         // notify container
 509         if (notifyContainer) {
 510             threadContainer().onExit(this);
 511         }
 512 
 513         // clear references to thread locals
 514         clearReferences();
 515     }
 516 
 517     /**
 518      * Schedules this {@code VirtualThread} to execute.
 519      *

 529 
 530         // bind thread to container
 531         assert threadContainer() == null;
 532         setThreadContainer(container);
 533 
 534         // start thread
 535         boolean addedToContainer = false;
 536         boolean started = false;
 537         try {
 538             container.onStart(this);  // may throw
 539             addedToContainer = true;
 540 
 541             // scoped values may be inherited
 542             inheritScopedValueBindings(container);
 543 
 544             // submit task to run thread
 545             submitRunContinuation();
 546             started = true;
 547         } finally {
 548             if (!started) {
 549                 setState(TERMINATED);
 550                 afterTerminate(addedToContainer, /*executed*/false);
 551             }
 552         }
 553     }
 554 
 555     @Override
 556     public void start() {
 557         start(ThreadContainers.root());
 558     }
 559 
 560     @Override
 561     public void run() {
 562         // do nothing
 563     }
 564 
 565     /**
 566      * Parks until unparked or interrupted. If already unparked then the parking
 567      * permit is consumed and this method completes immediately (meaning it doesn't
 568      * yield). It also completes immediately if the interrupt status is set.
 569      */
 570     @Override

 598      * Parks up to the given waiting time or until unparked or interrupted.
 599      * If already unparked then the parking permit is consumed and this method
 600      * completes immediately (meaning it doesn't yield). It also completes immediately
 601      * if the interrupt status is set or the waiting time is {@code <= 0}.
 602      *
 603      * @param nanos the maximum number of nanoseconds to wait.
 604      */
 605     @Override
 606     void parkNanos(long nanos) {
 607         assert Thread.currentThread() == this;
 608 
 609         // complete immediately if parking permit available or interrupted
 610         if (getAndSetParkPermit(false) || interrupted)
 611             return;
 612 
 613         // park the thread for the waiting time
 614         if (nanos > 0) {
 615             long startTime = System.nanoTime();
 616 
 617             boolean yielded = false;
 618             Future<?> unparker = scheduleUnpark(this::unpark, nanos);
 619             setState(PARKING);
 620             try {
 621                 yielded = yieldContinuation();  // may throw
 622             } finally {
 623                 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 624                 if (!yielded) {
 625                     assert state() == PARKING;
 626                     setState(RUNNING);
 627                 }
 628                 cancel(unparker);
 629             }
 630 
 631             // park on carrier thread for remaining time when pinned
 632             if (!yielded) {
 633                 long remainingNanos = nanos - (System.nanoTime() - startTime);
 634                 parkOnCarrierThread(true, remainingNanos);
 635             }
 636         }
 637     }
 638 
 639     /**
 640      * Parks the current carrier thread up to the given waiting time or until
 641      * unparked or interrupted. If the virtual thread is interrupted then the
 642      * interrupt status will be propagated to the carrier thread.
 643      * @param timed true for a timed park, false for untimed
 644      * @param nanos the waiting time in nanoseconds
 645      */
 646     private void parkOnCarrierThread(boolean timed, long nanos) {
 647         assert state() == RUNNING;
 648 
 649         VirtualThreadPinnedEvent event;
 650         try {
 651             event = new VirtualThreadPinnedEvent();
 652             event.begin();
 653         } catch (OutOfMemoryError e) {
 654             event = null;
 655         }
 656 
 657         setState(PINNED);
 658         try {
 659             if (!parkPermit) {
 660                 if (!timed) {
 661                     U.park(false, 0);
 662                 } else if (nanos > 0) {
 663                     U.park(false, nanos);
 664                 }
 665             }
 666         } finally {
 667             setState(RUNNING);
 668         }
 669 
 670         // consume parking permit
 671         setParkPermit(false);
 672 
 673         if (event != null) {
 674             try {
 675                 event.commit();
 676             } catch (OutOfMemoryError e) {
 677                 // ignore
 678             }
 679         }
 680     }
 681 
 682     /**
 683      * Schedule an unpark task to run after a given delay.
 684      */
 685     @ChangesCurrentThread
 686     private Future<?> scheduleUnpark(Runnable unparker, long nanos) {

 687         // need to switch to current carrier thread to avoid nested parking
 688         switchToCarrierThread();
 689         try {
 690             return UNPARKER.schedule(unparker, nanos, NANOSECONDS);
 691         } finally {
 692             switchToVirtualThread(this);
 693         }
 694     }
 695 
 696     /**
 697      * Cancels a task if it has not completed.
 698      */
 699     @ChangesCurrentThread
 700     private void cancel(Future<?> future) {
 701         if (!future.isDone()) {
 702             // need to switch to current carrier thread to avoid nested parking
 703             switchToCarrierThread();
 704             try {
 705                 future.cancel(false);
 706             } finally {
 707                 switchToVirtualThread(this);
 708             }
 709         }
 710     }
 711 
 712     /**
 713      * Re-enables this virtual thread for scheduling. If the virtual thread was
 714      * {@link #park() parked} then it will be unblocked, otherwise its next call
 715      * to {@code park} or {@linkplain #parkNanos(long) parkNanos} is guaranteed
 716      * not to block.
 717      * @throws RejectedExecutionException if the scheduler cannot accept a task
 718      */
 719     @Override
 720     @ChangesCurrentThread
 721     void unpark() {
 722         Thread currentThread = Thread.currentThread();
 723         if (!getAndSetParkPermit(true) && currentThread != this) {
 724             int s = state();
 725             if (s == PARKED && compareAndSetState(PARKED, RUNNABLE)) {

 726                 if (currentThread instanceof VirtualThread vthread) {
 727                     vthread.switchToCarrierThread();
 728                     try {
 729                         submitRunContinuation();
 730                     } finally {
 731                         switchToVirtualThread(vthread);
 732                     }
 733                 } else {
 734                     submitRunContinuation();
 735                 }
 736             } else if (s == PINNED) {
 737                 // unpark carrier thread when pinned.
 738                 synchronized (carrierThreadAccessLock()) {
 739                     Thread carrier = carrierThread;
 740                     if (carrier != null && state() == PINNED) {
 741                         U.unpark(carrier);
 742                     }
 743                 }
 744             }
 745         }
 746     }
 747 
 748     /**
 749      * Attempts to yield the current virtual thread (Thread.yield).
 750      */
 751     void tryYield() {
 752         assert Thread.currentThread() == this;
 753         setState(YIELDING);
 754         boolean yielded = false;
 755         try {
 756             yielded = yieldContinuation();  // may throw
 757         } finally {
 758             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 759             if (!yielded) {
 760                 assert state() == YIELDING;

 857     @Override
 858     public boolean isInterrupted() {
 859         return interrupted;
 860     }
 861 
 862     @Override
 863     boolean getAndClearInterrupt() {
 864         assert Thread.currentThread() == this;
 865         boolean oldValue = interrupted;
 866         if (oldValue) {
 867             synchronized (interruptLock) {
 868                 interrupted = false;
 869                 carrierThread.clearInterrupt();
 870             }
 871         }
 872         return oldValue;
 873     }
 874 
 875     @Override
 876     Thread.State threadState() {
 877         switch (state()) {

 878             case NEW:
 879                 return Thread.State.NEW;
 880             case STARTED:
 881                 // return NEW if thread container not yet set
 882                 if (threadContainer() == null) {
 883                     return Thread.State.NEW;
 884                 } else {
 885                     return Thread.State.RUNNABLE;
 886                 }
 887             case RUNNABLE:
 888             case RUNNABLE_SUSPENDED:
 889                 // runnable, not mounted
 890                 return Thread.State.RUNNABLE;
 891             case RUNNING:
 892                 // if mounted then return state of carrier thread
 893                 synchronized (carrierThreadAccessLock()) {
 894                     Thread carrierThread = this.carrierThread;
 895                     if (carrierThread != null) {
 896                         return carrierThread.threadState();
 897                     }
 898                 }
 899                 // runnable, mounted
 900                 return Thread.State.RUNNABLE;
 901             case PARKING:

 902             case YIELDING:
 903                 // runnable, mounted, not yet waiting
 904                 return Thread.State.RUNNABLE;
 905             case PARKED:
 906             case PARKED_SUSPENDED:
 907             case PINNED:
 908                 return Thread.State.WAITING;



 909             case TERMINATED:
 910                 return Thread.State.TERMINATED;
 911             default:
 912                 throw new InternalError();
 913         }
 914     }
 915 
 916     @Override
 917     boolean alive() {
 918         int s = state;
 919         return (s != NEW && s != TERMINATED);
 920     }
 921 
 922     @Override
 923     boolean isTerminated() {
 924         return (state == TERMINATED);
 925     }
 926 
 927     @Override
 928     StackTraceElement[] asyncGetStackTrace() {
 929         StackTraceElement[] stackTrace;
 930         do {
 931             stackTrace = (carrierThread != null)
 932                     ? super.asyncGetStackTrace()  // mounted
 933                     : tryGetStackTrace();         // unmounted
 934             if (stackTrace == null) {
 935                 Thread.yield();
 936             }
 937         } while (stackTrace == null);
 938         return stackTrace;
 939     }
 940 
 941     /**
 942      * Returns the stack trace for this virtual thread if it is unmounted.
 943      * Returns null if the thread is in another state.
 944      */
 945     private StackTraceElement[] tryGetStackTrace() {
 946         int initialState = state();
 947         return switch (initialState) {
 948             case RUNNABLE, PARKED -> {
 949                 int suspendedState = initialState | SUSPENDED;
 950                 if (compareAndSetState(initialState, suspendedState)) {
 951                     try {
 952                         yield cont.getStackTrace();
 953                     } finally {
 954                         assert state == suspendedState;
 955                         setState(initialState);
 956 
 957                         // re-submit if runnable
 958                         // re-submit if unparked while suspended
 959                         if (initialState == RUNNABLE
 960                             || (parkPermit && compareAndSetState(PARKED, RUNNABLE))) {
 961                             try {
 962                                 submitRunContinuation();
 963                             } catch (RejectedExecutionException ignore) { }
 964                         }
 965                     }
 966                 }
 967                 yield null;
 968             }
 969             case NEW, STARTED, TERMINATED ->  new StackTraceElement[0];  // empty stack
 970             default -> null;































 971         };




 972     }
 973 
 974     @Override
 975     public String toString() {
 976         StringBuilder sb = new StringBuilder("VirtualThread[#");
 977         sb.append(threadId());
 978         String name = getName();
 979         if (!name.isEmpty()) {
 980             sb.append(",");
 981             sb.append(name);
 982         }
 983         sb.append("]/");
 984         Thread carrier = carrierThread;
 985         if (carrier != null) {
 986             // include the carrier thread state and name when mounted
 987             synchronized (carrierThreadAccessLock()) {
 988                 carrier = carrierThread;
 989                 if (carrier != null) {
 990                     String stateAsString = carrier.threadState().toString();
 991                     sb.append(stateAsString.toLowerCase(Locale.ROOT));

  69     private static final Unsafe U = Unsafe.getUnsafe();
  70     private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
  71     private static final ForkJoinPool DEFAULT_SCHEDULER = createDefaultScheduler();
  72     private static final ScheduledExecutorService UNPARKER = createDelayedTaskScheduler();
  73     private static final int TRACE_PINNING_MODE = tracePinningMode();
  74 
  75     private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
  76     private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
  77     private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
  78     private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
  79 
  80     // scheduler and continuation
  81     private final Executor scheduler;
  82     private final Continuation cont;
  83     private final Runnable runContinuation;
  84 
  85     // virtual thread state, accessed by VM
  86     private volatile int state;
  87 
  88     /*
  89      * Virtual thread state transitions:
  90      *
  91      *      NEW -> STARTED         // Thread.start, schedule to run
  92      *  STARTED -> TERMINATED      // failed to start
  93      *  STARTED -> RUNNING         // first run
  94      *  RUNNING -> TERMINATED      // done
  95      *
  96      *  RUNNING -> PARKING         // Thread parking with LockSupport.park
  97      *  PARKING -> PARKED          // cont.yield successful, parked indefinitely
  98      *  PARKING -> PINNED          // cont.yield failed, parked indefinitely on carrier
  99      *   PARKED -> UNPARKED        // unparked, may be scheduled to continue
 100      *   PINNED -> RUNNING         // unparked, continue execution on same carrier
 101      * UNPARKED -> RUNNING         // continue execution after park
 102      *
 103      *       RUNNING -> TIMED_PARKING   // Thread parking with LockSupport.parkNanos
 104      * TIMED_PARKING -> TIMED_PARKED    // cont.yield successful, timed-parked
 105      * TIMED_PARKING -> TIMED_PINNED    // cont.yield failed, timed-parked on carrier
 106      *  TIMED_PARKED -> UNPARKED        // unparked, may be scheduled to continue
 107      *  TIMED_PINNED -> RUNNING         // unparked, continue execution on same carrier
 108      *
 109      *  RUNNING -> YIELDING        // Thread.yield
 110      * YIELDING -> YIELDED         // cont.yield successful, may be scheduled to continue
 111      * YIELDING -> RUNNING         // cont.yield failed
 112      *  YIELDED -> RUNNING         // continue execution after Thread.yield

 113      */
 114     private static final int NEW      = 0;
 115     private static final int STARTED  = 1;
 116     private static final int RUNNING  = 2;     // runnable-mounted
 117 
 118     // untimed and timed parking
 119     private static final int PARKING       = 3;
 120     private static final int PARKED        = 4;     // unmounted
 121     private static final int PINNED        = 5;     // mounted
 122     private static final int TIMED_PARKING = 6;
 123     private static final int TIMED_PARKED  = 7;     // unmounted
 124     private static final int TIMED_PINNED  = 8;     // mounted
 125     private static final int UNPARKED      = 9;     // unmounted but runnable
 126 
 127     // Thread.yield
 128     private static final int YIELDING = 10;
 129     private static final int YIELDED  = 11;         // unmounted but runnable
 130 
 131     private static final int TERMINATED = 99;  // final state
 132 
 133     // can be suspended from scheduling when unmounted
 134     private static final int SUSPENDED = 1 << 8;


 135 
 136     // parking permit
 137     private volatile boolean parkPermit;
 138 
 139     // carrier thread when mounted, accessed by VM
 140     private volatile Thread carrierThread;
 141 
 142     // termination object when joining, created lazily if needed
 143     private volatile CountDownLatch termination;
 144 
 145     /**
 146      * Returns the continuation scope used for virtual threads.
 147      */
 148     static ContinuationScope continuationScope() {
 149         return VTHREAD_SCOPE;
 150     }
 151 
 152     /**
 153      * Creates a new {@code VirtualThread} to run the given task with the given
 154      * scheduler. If the given scheduler is {@code null} and the current thread

 174                 scheduler = DEFAULT_SCHEDULER;
 175             }
 176         }
 177 
 178         this.scheduler = scheduler;
 179         this.cont = new VThreadContinuation(this, task);
 180         this.runContinuation = this::runContinuation;
 181     }
 182 
 183     /**
 184      * The continuation that a virtual thread executes.
 185      */
 186     private static class VThreadContinuation extends Continuation {
 187         VThreadContinuation(VirtualThread vthread, Runnable task) {
 188             super(VTHREAD_SCOPE, wrap(vthread, task));
 189         }
 190         @Override
 191         protected void onPinned(Continuation.Pinned reason) {
 192             if (TRACE_PINNING_MODE > 0) {
 193                 boolean printAll = (TRACE_PINNING_MODE == 1);
 194                 VirtualThread vthread = (VirtualThread) Thread.currentThread();
 195                 int oldState = vthread.state();
 196                 try {
 197                     // avoid printing when in transition states
 198                     vthread.setState(RUNNING);
 199                     PinnedThreadPrinter.printStackTrace(System.out, reason, printAll);
 200                 } finally {
 201                     vthread.setState(oldState);
 202                 }
 203             }
 204         }
 205         private static Runnable wrap(VirtualThread vthread, Runnable task) {
 206             return new Runnable() {
 207                 @Hidden
 208                 public void run() {
 209                     vthread.run(task);
 210                 }
 211             };
 212         }
 213     }
 214 
 215     /**
 216      * Runs or continues execution on the current thread. The virtual thread is mounted
 217      * on the current thread before the task runs or continues. It unmounts when the
 218      * task completes or yields.
 219      */
 220     @ChangesCurrentThread
 221     private void runContinuation() {
 222         // the carrier must be a platform thread
 223         if (Thread.currentThread().isVirtual()) {
 224             throw new WrongThreadException();
 225         }
 226 
 227         // set state to RUNNING
 228         int initialState = state();
 229         if (initialState == STARTED || initialState == UNPARKED || initialState == YIELDED) {
 230             // newly started or continue after parking/blocking/Thread.yield
 231             if (!compareAndSetState(initialState, RUNNING)) {
 232                 return;
 233             }
 234             // consume parking permit when continuing after parking
 235             if (initialState == UNPARKED) {
 236                 setParkPermit(false);
 237             }
 238         } else {
 239             // not runnable
 240             return;
 241         }
 242 
 243         mount();


 244         try {
 245             cont.run();
 246         } finally {
 247             unmount();
 248             if (cont.isDone()) {
 249                 afterDone();
 250             } else {
 251                 afterYield();
 252             }
 253         }
 254     }
 255 
 256     /**
 257      * Submits the runContinuation task to the scheduler. For the default scheduler,
 258      * and calling it on a worker thread, the task will be pushed to the local queue,
 259      * otherwise it will be pushed to an external submission queue.

 260      * @throws RejectedExecutionException
 261      */
 262     private void submitRunContinuation() {
 263         try {
 264             scheduler.execute(runContinuation);
 265         } catch (RejectedExecutionException ree) {
 266             submitFailed(ree);
 267             throw ree;
 268         }
 269     }
 270 
 271     /**
 272      * Submits the runContinuation task to given scheduler with a lazy submit.
 273      * @throws RejectedExecutionException
 274      * @see ForkJoinPool#lazySubmit(ForkJoinTask)
 275      */
 276     private void lazySubmitRunContinuation(ForkJoinPool pool) {
 277         try {
 278             pool.lazySubmit(ForkJoinTask.adapt(runContinuation));
 279         } catch (RejectedExecutionException ree) {
 280             submitFailed(ree);
 281             throw ree;
 282         }
 283     }
 284 
 285     /**
 286      * Submits the runContinuation task to the given scheduler as an external submit.
 287      * @throws RejectedExecutionException
 288      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 289      */
 290     private void externalSubmitRunContinuation(ForkJoinPool pool) {
 291         try {
 292             pool.externalSubmit(ForkJoinTask.adapt(runContinuation));
 293         } catch (RejectedExecutionException ree) {
 294             submitFailed(ree);
 295             throw ree;
 296         }
 297     }
 298 
 299     /**
 300      * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
 301      */
 302     private void submitFailed(RejectedExecutionException ree) {
 303         var event = new VirtualThreadSubmitFailedEvent();
 304         if (event.isEnabled()) {
 305             event.javaThreadId = threadId();
 306             event.exceptionMessage = ree.getMessage();
 307             event.commit();
 308         }
 309     }
 310 
 311     /**
 312      * Runs a task in the context of this virtual thread.


 313      */

 314     private void run(Runnable task) {
 315         assert Thread.currentThread() == this && state == RUNNING;
 316 
 317         // notify JVMTI, may post VirtualThreadStart event

 318         notifyJvmtiStart();
 319 
 320         // emit JFR event if enabled
 321         if (VirtualThreadStartEvent.isTurnedOn()) {
 322             var event = new VirtualThreadStartEvent();
 323             event.javaThreadId = threadId();
 324             event.commit();
 325         }
 326 
 327         Object bindings = Thread.scopedValueBindings();
 328         try {
 329             runWith(bindings, task);
 330         } catch (Throwable exc) {
 331             dispatchUncaughtException(exc);
 332         } finally {
 333             try {
 334                 // pop any remaining scopes from the stack, this may block
 335                 StackableScope.popAll();
 336 
 337                 // emit JFR event if enabled
 338                 if (VirtualThreadEndEvent.isTurnedOn()) {
 339                     var event = new VirtualThreadEndEvent();
 340                     event.javaThreadId = threadId();
 341                     event.commit();
 342                 }
 343 
 344             } finally {
 345                 // notify JVMTI, may post VirtualThreadEnd event
 346                 notifyJvmtiEnd();




 347             }
 348         }
 349     }
 350 
 351     /**
 352      * Mounts this virtual thread onto the current platform thread. On
 353      * return, the current thread is the virtual thread.
 354      */
 355     @ChangesCurrentThread
 356     @ReservedStackAccess
 357     private void mount() {
 358         // notify JVMTI before mount
 359         notifyJvmtiMount(/*hide*/true);
 360 
 361         // sets the carrier thread
 362         Thread carrier = Thread.currentCarrierThread();
 363         setCarrierThread(carrier);
 364 
 365         // sync up carrier thread interrupt status if needed
 366         if (interrupted) {
 367             carrier.setInterrupt();
 368         } else if (carrier.isInterrupted()) {
 369             synchronized (interruptLock) {
 370                 // need to recheck interrupt status
 371                 if (!interrupted) {
 372                     carrier.clearInterrupt();
 373                 }
 374             }
 375         }
 376 
 377         // set Thread.currentThread() to return this virtual thread
 378         carrier.setCurrentThread(this);
 379     }
 380 
 381     /**
 382      * Unmounts this virtual thread from the carrier. On return, the
 383      * current thread is the current platform thread.
 384      */
 385     @ChangesCurrentThread
 386     @ReservedStackAccess
 387     private void unmount() {
 388         // set Thread.currentThread() to return the platform thread
 389         Thread carrier = this.carrierThread;
 390         carrier.setCurrentThread(carrier);
 391 
 392         // break connection to carrier thread, synchronized with interrupt
 393         synchronized (interruptLock) {
 394             setCarrierThread(null);
 395         }
 396         carrier.clearInterrupt();
 397 
 398         // notify JVMTI after unmount
 399         notifyJvmtiUnmount(/*hide*/false);
 400     }
 401 
 402     /**
 403      * Sets the current thread to the current carrier thread.
 404      */
 405     @ChangesCurrentThread
 406     @JvmtiMountTransition
 407     private void switchToCarrierThread() {
 408         notifyJvmtiHideFrames(true);
 409         Thread carrier = this.carrierThread;
 410         assert Thread.currentThread() == this
 411                 && carrier == Thread.currentCarrierThread();
 412         carrier.setCurrentThread(carrier);
 413     }
 414 
 415     /**
 416      * Sets the current thread to the given virtual thread.
 417      */
 418     @ChangesCurrentThread
 419     @JvmtiMountTransition

 422         assert carrier == Thread.currentCarrierThread();
 423         carrier.setCurrentThread(vthread);
 424         notifyJvmtiHideFrames(false);
 425     }
 426 
 427     /**
 428      * Executes the given value returning task on the current carrier thread.
 429      */
 430     @ChangesCurrentThread
 431     <V> V executeOnCarrierThread(Callable<V> task) throws Exception {
 432         assert Thread.currentThread() == this;
 433         switchToCarrierThread();
 434         try {
 435             return task.call();
 436         } finally {
 437             switchToVirtualThread(this);
 438         }
 439      }
 440 
 441     /**
 442      * Invokes Continuation.yield, notifying JVMTI (if enabled) to hide frames until
 443      * the continuation continues.

 444      */
 445     @Hidden

 446     private boolean yieldContinuation() {

 447         notifyJvmtiUnmount(/*hide*/true);

 448         try {
 449             return Continuation.yield(VTHREAD_SCOPE);
 450         } finally {


 451             notifyJvmtiMount(/*hide*/false);
 452         }
 453     }
 454 
 455     /**
 456      * Invoked after the continuation yields. If parking then it sets the state
 457      * and also re-submits the task to continue if unparked while parking.
 458      * If yielding due to Thread.yield then it just submits the task to continue.
 459      */
 460     private void afterYield() {
 461         assert carrierThread == null;

 462 
 463         int s = state();

 464 
 465         // LockSupport.park/parkNanos
 466         if (s == PARKING || s == TIMED_PARKING) {
 467             int newState = (s == PARKING) ? PARKED : TIMED_PARKED;
 468             setState(newState);
 469 
 470             // may have been unparked while parking
 471             if (parkPermit && compareAndSetState(newState, UNPARKED)) {
 472                 // lazy submit to continue on the current thread as carrier if possible
 473                 if (currentThread() instanceof CarrierThread ct) {
 474                     lazySubmitRunContinuation(ct.getPool());
 475                 } else {
 476                     submitRunContinuation();
 477                 }
 478 
 479             }
 480             return;
 481         }
 482 
 483         // Thread.yield
 484         if (s == YIELDING) {
 485             setState(YIELDED);
 486 
 487             // external submit if there are no tasks in the local task queue
 488             if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
 489                 externalSubmitRunContinuation(ct.getPool());
 490             } else {
 491                 submitRunContinuation();
 492             }
 493             return;
 494         }
 495 
 496         assert false;
 497     }
 498 
 499     /**
 500      * Invoked after the continuation completes.

 501      */
 502     private void afterDone() {
 503         afterDone(true);
 504     }
 505 
 506     /**
 507      * Invoked after the continuation completes (or start failed). Sets the thread
 508      * state to TERMINATED and notifies anyone waiting for the thread to terminate.
 509      *
 510      * @param notifyContainer true if its container should be notified

 511      */
 512     private void afterDone(boolean notifyContainer) {
 513         assert carrierThread == null;
 514         setState(TERMINATED);



 515 
 516         // notify anyone waiting for this virtual thread to terminate
 517         CountDownLatch termination = this.termination;
 518         if (termination != null) {
 519             assert termination.getCount() == 1;
 520             termination.countDown();
 521         }
 522 
 523         // notify container
 524         if (notifyContainer) {
 525             threadContainer().onExit(this);
 526         }
 527 
 528         // clear references to thread locals
 529         clearReferences();
 530     }
 531 
 532     /**
 533      * Schedules this {@code VirtualThread} to execute.
 534      *

 544 
 545         // bind thread to container
 546         assert threadContainer() == null;
 547         setThreadContainer(container);
 548 
 549         // start thread
 550         boolean addedToContainer = false;
 551         boolean started = false;
 552         try {
 553             container.onStart(this);  // may throw
 554             addedToContainer = true;
 555 
 556             // scoped values may be inherited
 557             inheritScopedValueBindings(container);
 558 
 559             // submit task to run thread
 560             submitRunContinuation();
 561             started = true;
 562         } finally {
 563             if (!started) {
 564                 afterDone(addedToContainer);

 565             }
 566         }
 567     }
 568 
 569     @Override
 570     public void start() {
 571         start(ThreadContainers.root());
 572     }
 573 
 574     @Override
 575     public void run() {
 576         // do nothing
 577     }
 578 
 579     /**
 580      * Parks until unparked or interrupted. If already unparked then the parking
 581      * permit is consumed and this method completes immediately (meaning it doesn't
 582      * yield). It also completes immediately if the interrupt status is set.
 583      */
 584     @Override

 612      * Parks up to the given waiting time or until unparked or interrupted.
 613      * If already unparked then the parking permit is consumed and this method
 614      * completes immediately (meaning it doesn't yield). It also completes immediately
 615      * if the interrupt status is set or the waiting time is {@code <= 0}.
 616      *
 617      * @param nanos the maximum number of nanoseconds to wait.
 618      */
 619     @Override
 620     void parkNanos(long nanos) {
 621         assert Thread.currentThread() == this;
 622 
 623         // complete immediately if parking permit available or interrupted
 624         if (getAndSetParkPermit(false) || interrupted)
 625             return;
 626 
 627         // park the thread for the waiting time
 628         if (nanos > 0) {
 629             long startTime = System.nanoTime();
 630 
 631             boolean yielded = false;
 632             Future<?> unparker = scheduleUnpark(nanos);  // may throw OOME
 633             setState(TIMED_PARKING);
 634             try {
 635                 yielded = yieldContinuation();  // may throw
 636             } finally {
 637                 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 638                 if (!yielded) {
 639                     assert state() == TIMED_PARKING;
 640                     setState(RUNNING);
 641                 }
 642                 cancel(unparker);
 643             }
 644 
 645             // park on carrier thread for remaining time when pinned
 646             if (!yielded) {
 647                 long remainingNanos = nanos - (System.nanoTime() - startTime);
 648                 parkOnCarrierThread(true, remainingNanos);
 649             }
 650         }
 651     }
 652 
 653     /**
 654      * Parks the current carrier thread up to the given waiting time or until
 655      * unparked or interrupted. If the virtual thread is interrupted then the
 656      * interrupt status will be propagated to the carrier thread.
 657      * @param timed true for a timed park, false for untimed
 658      * @param nanos the waiting time in nanoseconds
 659      */
 660     private void parkOnCarrierThread(boolean timed, long nanos) {
 661         assert state() == RUNNING;
 662 
 663         VirtualThreadPinnedEvent event;
 664         try {
 665             event = new VirtualThreadPinnedEvent();
 666             event.begin();
 667         } catch (OutOfMemoryError e) {
 668             event = null;
 669         }
 670 
 671         setState(timed ? TIMED_PINNED : PINNED);
 672         try {
 673             if (!parkPermit) {
 674                 if (!timed) {
 675                     U.park(false, 0);
 676                 } else if (nanos > 0) {
 677                     U.park(false, nanos);
 678                 }
 679             }
 680         } finally {
 681             setState(RUNNING);
 682         }
 683 
 684         // consume parking permit
 685         setParkPermit(false);
 686 
 687         if (event != null) {
 688             try {
 689                 event.commit();
 690             } catch (OutOfMemoryError e) {
 691                 // ignore
 692             }
 693         }
 694     }
 695 
 696     /**
 697      * Schedule this virtual thread to be unparked after a given delay.
 698      */
 699     @ChangesCurrentThread
 700     private Future<?> scheduleUnpark(long nanos) {
 701         assert Thread.currentThread() == this;
 702         // need to switch to current carrier thread to avoid nested parking
 703         switchToCarrierThread();
 704         try {
 705             return UNPARKER.schedule(this::unpark, nanos, NANOSECONDS);
 706         } finally {
 707             switchToVirtualThread(this);
 708         }
 709     }
 710 
 711     /**
 712      * Cancels a task if it has not completed.
 713      */
 714     @ChangesCurrentThread
 715     private void cancel(Future<?> future) {
 716         if (!future.isDone()) {
 717             // need to switch to current carrier thread to avoid nested parking
 718             switchToCarrierThread();
 719             try {
 720                 future.cancel(false);
 721             } finally {
 722                 switchToVirtualThread(this);
 723             }
 724         }
 725     }
 726 
 727     /**
 728      * Re-enables this virtual thread for scheduling. If the virtual thread was
 729      * {@link #park() parked} then it will be unblocked, otherwise its next call
 730      * to {@code park} or {@linkplain #parkNanos(long) parkNanos} is guaranteed
 731      * not to block.
 732      * @throws RejectedExecutionException if the scheduler cannot accept a task
 733      */
 734     @Override
 735     @ChangesCurrentThread
 736     void unpark() {
 737         Thread currentThread = Thread.currentThread();
 738         if (!getAndSetParkPermit(true) && currentThread != this) {
 739             int s = state();
 740             boolean parked = (s == PARKED) || (s == TIMED_PARKED);
 741             if (parked && compareAndSetState(s, UNPARKED)) {
 742                 if (currentThread instanceof VirtualThread vthread) {
 743                     vthread.switchToCarrierThread();
 744                     try {
 745                         submitRunContinuation();
 746                     } finally {
 747                         switchToVirtualThread(vthread);
 748                     }
 749                 } else {
 750                     submitRunContinuation();
 751                 }
 752             } else if ((s == PINNED) || (s == TIMED_PINNED)) {
 753                 // unpark carrier thread when pinned
 754                 synchronized (carrierThreadAccessLock()) {
 755                     Thread carrier = carrierThread;
 756                     if (carrier != null && ((s = state()) == PINNED || s == TIMED_PINNED)) {
 757                         U.unpark(carrier);
 758                     }
 759                 }
 760             }
 761         }
 762     }
 763 
 764     /**
 765      * Attempts to yield the current virtual thread (Thread.yield).
 766      */
 767     void tryYield() {
 768         assert Thread.currentThread() == this;
 769         setState(YIELDING);
 770         boolean yielded = false;
 771         try {
 772             yielded = yieldContinuation();  // may throw
 773         } finally {
 774             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 775             if (!yielded) {
 776                 assert state() == YIELDING;

 873     @Override
 874     public boolean isInterrupted() {
 875         return interrupted;
 876     }
 877 
 878     @Override
 879     boolean getAndClearInterrupt() {
 880         assert Thread.currentThread() == this;
 881         boolean oldValue = interrupted;
 882         if (oldValue) {
 883             synchronized (interruptLock) {
 884                 interrupted = false;
 885                 carrierThread.clearInterrupt();
 886             }
 887         }
 888         return oldValue;
 889     }
 890 
 891     @Override
 892     Thread.State threadState() {
 893         int s = state();
 894         switch (s & ~SUSPENDED) {
 895             case NEW:
 896                 return Thread.State.NEW;
 897             case STARTED:
 898                 // return NEW if thread container not yet set
 899                 if (threadContainer() == null) {
 900                     return Thread.State.NEW;
 901                 } else {
 902                     return Thread.State.RUNNABLE;
 903                 }
 904             case UNPARKED:
 905             case YIELDED:
 906                 // runnable, not mounted
 907                 return Thread.State.RUNNABLE;
 908             case RUNNING:
 909                 // if mounted then return state of carrier thread
 910                 synchronized (carrierThreadAccessLock()) {
 911                     Thread carrierThread = this.carrierThread;
 912                     if (carrierThread != null) {
 913                         return carrierThread.threadState();
 914                     }
 915                 }
 916                 // runnable, mounted
 917                 return Thread.State.RUNNABLE;
 918             case PARKING:
 919             case TIMED_PARKING:
 920             case YIELDING:
 921                 // runnable, in transition
 922                 return Thread.State.RUNNABLE;
 923             case PARKED:

 924             case PINNED:
 925                 return State.WAITING;
 926             case TIMED_PARKED:
 927             case TIMED_PINNED:
 928                 return State.TIMED_WAITING;
 929             case TERMINATED:
 930                 return Thread.State.TERMINATED;
 931             default:
 932                 throw new InternalError();
 933         }
 934     }
 935 
 936     @Override
 937     boolean alive() {
 938         int s = state;
 939         return (s != NEW && s != TERMINATED);
 940     }
 941 
 942     @Override
 943     boolean isTerminated() {
 944         return (state == TERMINATED);
 945     }
 946 
 947     @Override
 948     StackTraceElement[] asyncGetStackTrace() {
 949         StackTraceElement[] stackTrace;
 950         do {
 951             stackTrace = (carrierThread != null)
 952                     ? super.asyncGetStackTrace()  // mounted
 953                     : tryGetStackTrace();         // unmounted
 954             if (stackTrace == null) {
 955                 Thread.yield();
 956             }
 957         } while (stackTrace == null);
 958         return stackTrace;
 959     }
 960 
 961     /**
 962      * Returns the stack trace for this virtual thread if it is unmounted.
 963      * Returns null if the thread is mounted or in transition.
 964      */
 965     private StackTraceElement[] tryGetStackTrace() {
 966         int initialState = state() & ~SUSPENDED;
 967         switch (initialState) {
 968             case NEW, STARTED, TERMINATED -> {
 969                 return new StackTraceElement[0];  // unmounted, empty stack
 970             }
 971             case RUNNING, PINNED, TIMED_PINNED -> {
 972                 return null;   // mounted
 973             }
 974             case PARKED, TIMED_PARKED -> {
 975                 // unmounted, not runnable












 976             }
 977             case UNPARKED, YIELDED -> {
 978                 // unmounted, runnable
 979             }
 980             case PARKING, TIMED_PARKING, YIELDING -> {
 981                 return null;  // in transition
 982             }
 983             default -> throw new InternalError("" + initialState);
 984         }
 985 
 986         // thread is unmounted, prevent it from continuing
 987         int suspendedState = initialState | SUSPENDED;
 988         if (!compareAndSetState(initialState, suspendedState)) {
 989             return null;
 990         }
 991 
 992         // get stack trace and restore state
 993         StackTraceElement[] stack;
 994         try {
 995             stack = cont.getStackTrace();
 996         } finally {
 997             assert state == suspendedState;
 998             setState(initialState);
 999         }
1000         boolean resubmit = switch (initialState) {
1001             case UNPARKED, YIELDED -> {
1002                 // resubmit as task may have run while suspended
1003                 yield true;
1004             }
1005             case PARKED, TIMED_PARKED -> {
1006                 // resubmit if unparked while suspended
1007                 yield parkPermit && compareAndSetState(initialState, UNPARKED);
1008             }
1009             default -> throw new InternalError();
1010         };
1011         if (resubmit) {
1012             submitRunContinuation();
1013         }
1014         return stack;
1015     }
1016 
1017     @Override
1018     public String toString() {
1019         StringBuilder sb = new StringBuilder("VirtualThread[#");
1020         sb.append(threadId());
1021         String name = getName();
1022         if (!name.isEmpty()) {
1023             sb.append(",");
1024             sb.append(name);
1025         }
1026         sb.append("]/");
1027         Thread carrier = carrierThread;
1028         if (carrier != null) {
1029             // include the carrier thread state and name when mounted
1030             synchronized (carrierThreadAccessLock()) {
1031                 carrier = carrierThread;
1032                 if (carrier != null) {
1033                     String stateAsString = carrier.threadState().toString();
1034                     sb.append(stateAsString.toLowerCase(Locale.ROOT));
< prev index next >