1 /*
   2  * Copyright (c) 2018, 2023, 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.security.AccessController;
  28 import java.security.PrivilegedAction;
  29 import java.util.Locale;
  30 import java.util.Objects;
  31 import java.util.concurrent.Callable;
  32 import java.util.concurrent.CountDownLatch;
  33 import java.util.concurrent.Executor;
  34 import java.util.concurrent.Executors;
  35 import java.util.concurrent.ForkJoinPool;
  36 import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;
  37 import java.util.concurrent.ForkJoinTask;
  38 import java.util.concurrent.ForkJoinWorkerThread;
  39 import java.util.concurrent.Future;
  40 import java.util.concurrent.RejectedExecutionException;
  41 import java.util.concurrent.ScheduledExecutorService;
  42 import java.util.concurrent.ScheduledThreadPoolExecutor;
  43 import jdk.internal.event.VirtualThreadEndEvent;
  44 import jdk.internal.event.VirtualThreadPinnedEvent;
  45 import jdk.internal.event.VirtualThreadStartEvent;
  46 import jdk.internal.event.VirtualThreadSubmitFailedEvent;
  47 import jdk.internal.misc.CarrierThread;
  48 import jdk.internal.misc.InnocuousThread;
  49 import jdk.internal.misc.Unsafe;
  50 import jdk.internal.vm.Continuation;
  51 import jdk.internal.vm.ContinuationScope;
  52 import jdk.internal.vm.StackableScope;
  53 import jdk.internal.vm.ThreadContainer;
  54 import jdk.internal.vm.ThreadContainers;
  55 import jdk.internal.vm.annotation.ChangesCurrentThread;
  56 import jdk.internal.vm.annotation.Hidden;
  57 import jdk.internal.vm.annotation.IntrinsicCandidate;
  58 import jdk.internal.vm.annotation.JvmtiMountTransition;
  59 import jdk.internal.vm.annotation.ReservedStackAccess;
  60 import sun.nio.ch.Interruptible;
  61 import sun.security.action.GetPropertyAction;
  62 import static java.util.concurrent.TimeUnit.*;
  63 
  64 /**
  65  * A thread that is scheduled by the Java virtual machine rather than the operating
  66  * 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     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
 155      * is a platform thread then the newly created virtual thread will use the
 156      * default scheduler. If given scheduler is {@code null} and the current
 157      * thread is a virtual thread then the current thread's scheduler is used.
 158      *
 159      * @param scheduler the scheduler or null
 160      * @param name thread name
 161      * @param characteristics characteristics
 162      * @param task the task to execute
 163      */
 164     VirtualThread(Executor scheduler, String name, int characteristics, Runnable task) {
 165         super(name, characteristics, /*bound*/ false);
 166         Objects.requireNonNull(task);
 167 
 168         // choose scheduler if not specified
 169         if (scheduler == null) {
 170             Thread parent = Thread.currentThread();
 171             if (parent instanceof VirtualThread vparent) {
 172                 scheduler = vparent.scheduler;
 173             } else {
 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
 420     private void switchToVirtualThread(VirtualThread vthread) {
 421         Thread carrier = vthread.carrierThread;
 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      *
 535      * @throws IllegalStateException if the container is shutdown or closed
 536      * @throws IllegalThreadStateException if the thread has already been started
 537      * @throws RejectedExecutionException if the scheduler cannot accept a task
 538      */
 539     @Override
 540     void start(ThreadContainer container) {
 541         if (!compareAndSetState(NEW, STARTED)) {
 542             throw new IllegalThreadStateException("Already started");
 543         }
 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
 585     void park() {
 586         assert Thread.currentThread() == this;
 587 
 588         // complete immediately if parking permit available or interrupted
 589         if (getAndSetParkPermit(false) || interrupted)
 590             return;
 591 
 592         // park the thread
 593         boolean yielded = false;
 594         setState(PARKING);
 595         try {
 596             yielded = yieldContinuation();  // may throw
 597         } finally {
 598             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 599             if (!yielded) {
 600                 assert state() == PARKING;
 601                 setState(RUNNING);
 602             }
 603         }
 604 
 605         // park on the carrier thread when pinned
 606         if (!yielded) {
 607             parkOnCarrierThread(false, 0);
 608         }
 609     }
 610 
 611     /**
 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;
 777                 setState(RUNNING);
 778             }
 779         }
 780     }
 781 
 782     /**
 783      * Sleep the current thread for the given sleep time (in nanoseconds). If
 784      * nanos is 0 then the thread will attempt to yield.
 785      *
 786      * @implNote This implementation parks the thread for the given sleeping time
 787      * and will therefore be observed in PARKED state during the sleep. Parking
 788      * will consume the parking permit so this method makes available the parking
 789      * permit after the sleep. This may be observed as a spurious, but benign,
 790      * wakeup when the thread subsequently attempts to park.
 791      *
 792      * @param nanos the maximum number of nanoseconds to sleep
 793      * @throws InterruptedException if interrupted while sleeping
 794      */
 795     void sleepNanos(long nanos) throws InterruptedException {
 796         assert Thread.currentThread() == this && nanos >= 0;
 797         if (getAndClearInterrupt())
 798             throw new InterruptedException();
 799         if (nanos == 0) {
 800             tryYield();
 801         } else {
 802             // park for the sleep time
 803             try {
 804                 long remainingNanos = nanos;
 805                 long startNanos = System.nanoTime();
 806                 while (remainingNanos > 0) {
 807                     parkNanos(remainingNanos);
 808                     if (getAndClearInterrupt()) {
 809                         throw new InterruptedException();
 810                     }
 811                     remainingNanos = nanos - (System.nanoTime() - startNanos);
 812                 }
 813             } finally {
 814                 // may have been unparked while sleeping
 815                 setParkPermit(true);
 816             }
 817         }
 818     }
 819 
 820     /**
 821      * Waits up to {@code nanos} nanoseconds for this virtual thread to terminate.
 822      * A timeout of {@code 0} means to wait forever.
 823      *
 824      * @throws InterruptedException if interrupted while waiting
 825      * @return true if the thread has terminated
 826      */
 827     boolean joinNanos(long nanos) throws InterruptedException {
 828         if (state() == TERMINATED)
 829             return true;
 830 
 831         // ensure termination object exists, then re-check state
 832         CountDownLatch termination = getTermination();
 833         if (state() == TERMINATED)
 834             return true;
 835 
 836         // wait for virtual thread to terminate
 837         if (nanos == 0) {
 838             termination.await();
 839         } else {
 840             boolean terminated = termination.await(nanos, NANOSECONDS);
 841             if (!terminated) {
 842                 // waiting time elapsed
 843                 return false;
 844             }
 845         }
 846         assert state() == TERMINATED;
 847         return true;
 848     }
 849 
 850     @Override
 851     @SuppressWarnings("removal")
 852     public void interrupt() {
 853         if (Thread.currentThread() != this) {
 854             checkAccess();
 855             synchronized (interruptLock) {
 856                 interrupted = true;
 857                 Interruptible b = nioBlocker;
 858                 if (b != null) {
 859                     b.interrupt(this);
 860                 }
 861 
 862                 // interrupt carrier thread if mounted
 863                 Thread carrier = carrierThread;
 864                 if (carrier != null) carrier.setInterrupt();
 865             }
 866         } else {
 867             interrupted = true;
 868             carrierThread.setInterrupt();
 869         }
 870         unpark();
 871     }
 872 
 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));
1035                     sb.append('@');
1036                     sb.append(carrier.getName());
1037                 }
1038             }
1039         }
1040         // include virtual thread state when not mounted
1041         if (carrier == null) {
1042             String stateAsString = threadState().toString();
1043             sb.append(stateAsString.toLowerCase(Locale.ROOT));
1044         }
1045         return sb.toString();
1046     }
1047 
1048     @Override
1049     public int hashCode() {
1050         return (int) threadId();
1051     }
1052 
1053     @Override
1054     public boolean equals(Object obj) {
1055         return obj == this;
1056     }
1057 
1058     /**
1059      * Returns the termination object, creating it if needed.
1060      */
1061     private CountDownLatch getTermination() {
1062         CountDownLatch termination = this.termination;
1063         if (termination == null) {
1064             termination = new CountDownLatch(1);
1065             if (!U.compareAndSetReference(this, TERMINATION, null, termination)) {
1066                 termination = this.termination;
1067             }
1068         }
1069         return termination;
1070     }
1071 
1072     /**
1073      * Returns the lock object to synchronize on when accessing carrierThread.
1074      * The lock prevents carrierThread from being reset to null during unmount.
1075      */
1076     private Object carrierThreadAccessLock() {
1077         // return interruptLock as unmount has to coordinate with interrupt
1078         return interruptLock;
1079     }
1080 
1081     // -- wrappers for get/set of state, parking permit, and carrier thread --
1082 
1083     private int state() {
1084         return state;  // volatile read
1085     }
1086 
1087     private void setState(int newValue) {
1088         state = newValue;  // volatile write
1089     }
1090 
1091     private boolean compareAndSetState(int expectedValue, int newValue) {
1092         return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1093     }
1094 
1095     private void setParkPermit(boolean newValue) {
1096         if (parkPermit != newValue) {
1097             parkPermit = newValue;
1098         }
1099     }
1100 
1101     private boolean getAndSetParkPermit(boolean newValue) {
1102         if (parkPermit != newValue) {
1103             return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1104         } else {
1105             return newValue;
1106         }
1107     }
1108 
1109     private void setCarrierThread(Thread carrier) {
1110         // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1111         this.carrierThread = carrier;
1112     }
1113 
1114     // -- JVM TI support --
1115 
1116     @IntrinsicCandidate
1117     @JvmtiMountTransition
1118     private native void notifyJvmtiStart();
1119 
1120     @IntrinsicCandidate
1121     @JvmtiMountTransition
1122     private native void notifyJvmtiEnd();
1123 
1124     @IntrinsicCandidate
1125     @JvmtiMountTransition
1126     private native void notifyJvmtiMount(boolean hide);
1127 
1128     @IntrinsicCandidate
1129     @JvmtiMountTransition
1130     private native void notifyJvmtiUnmount(boolean hide);
1131 
1132     @IntrinsicCandidate
1133     @JvmtiMountTransition
1134     private native void notifyJvmtiHideFrames(boolean hide);
1135 
1136     private static native void registerNatives();
1137     static {
1138         registerNatives();
1139     }
1140 
1141     /**
1142      * Creates the default scheduler.
1143      */
1144     @SuppressWarnings("removal")
1145     private static ForkJoinPool createDefaultScheduler() {
1146         ForkJoinWorkerThreadFactory factory = pool -> {
1147             PrivilegedAction<ForkJoinWorkerThread> pa = () -> new CarrierThread(pool);
1148             return AccessController.doPrivileged(pa);
1149         };
1150         PrivilegedAction<ForkJoinPool> pa = () -> {
1151             int parallelism, maxPoolSize, minRunnable;
1152             String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1153             String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1154             String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1155             if (parallelismValue != null) {
1156                 parallelism = Integer.parseInt(parallelismValue);
1157             } else {
1158                 parallelism = Runtime.getRuntime().availableProcessors();
1159             }
1160             if (maxPoolSizeValue != null) {
1161                 maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1162                 parallelism = Integer.min(parallelism, maxPoolSize);
1163             } else {
1164                 maxPoolSize = Integer.max(parallelism, 256);
1165             }
1166             if (minRunnableValue != null) {
1167                 minRunnable = Integer.parseInt(minRunnableValue);
1168             } else {
1169                 minRunnable = Integer.max(parallelism / 2, 1);
1170             }
1171             Thread.UncaughtExceptionHandler handler = (t, e) -> { };
1172             boolean asyncMode = true; // FIFO
1173             return new ForkJoinPool(parallelism, factory, handler, asyncMode,
1174                          0, maxPoolSize, minRunnable, pool -> true, 30, SECONDS);
1175         };
1176         return AccessController.doPrivileged(pa);
1177     }
1178 
1179     /**
1180      * Creates the ScheduledThreadPoolExecutor used for timed unpark.
1181      */
1182     private static ScheduledExecutorService createDelayedTaskScheduler() {
1183         String propValue = GetPropertyAction.privilegedGetProperty("jdk.unparker.maxPoolSize");
1184         int poolSize;
1185         if (propValue != null) {
1186             poolSize = Integer.parseInt(propValue);
1187         } else {
1188             poolSize = 1;
1189         }
1190         ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor)
1191             Executors.newScheduledThreadPool(poolSize, task -> {
1192                 return InnocuousThread.newThread("VirtualThread-unparker", task);
1193             });
1194         stpe.setRemoveOnCancelPolicy(true);
1195         return stpe;
1196     }
1197 
1198     /**
1199      * Reads the value of the jdk.tracePinnedThreads property to determine if stack
1200      * traces should be printed when a carrier thread is pinned when a virtual thread
1201      * attempts to park.
1202      */
1203     private static int tracePinningMode() {
1204         String propValue = GetPropertyAction.privilegedGetProperty("jdk.tracePinnedThreads");
1205         if (propValue != null) {
1206             if (propValue.length() == 0 || "full".equalsIgnoreCase(propValue))
1207                 return 1;
1208             if ("short".equalsIgnoreCase(propValue))
1209                 return 2;
1210         }
1211         return 0;
1212     }
1213 }