< prev index next >

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

Print this page

   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.util.Locale;
  28 import java.util.Objects;
  29 import java.util.concurrent.CountDownLatch;
  30 import java.util.concurrent.Executor;
  31 import java.util.concurrent.Executors;
  32 import java.util.concurrent.ForkJoinPool;
  33 import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;
  34 import java.util.concurrent.ForkJoinTask;
  35 import java.util.concurrent.Future;
  36 import java.util.concurrent.RejectedExecutionException;
  37 import java.util.concurrent.ScheduledExecutorService;
  38 import java.util.concurrent.ScheduledThreadPoolExecutor;
  39 import java.util.concurrent.TimeUnit;
  40 import jdk.internal.event.VirtualThreadEndEvent;

  41 import jdk.internal.event.VirtualThreadStartEvent;
  42 import jdk.internal.event.VirtualThreadSubmitFailedEvent;

  43 import jdk.internal.misc.CarrierThread;
  44 import jdk.internal.misc.InnocuousThread;
  45 import jdk.internal.misc.Unsafe;
  46 import jdk.internal.vm.Continuation;
  47 import jdk.internal.vm.ContinuationScope;
  48 import jdk.internal.vm.StackableScope;
  49 import jdk.internal.vm.ThreadContainer;
  50 import jdk.internal.vm.ThreadContainers;
  51 import jdk.internal.vm.annotation.ChangesCurrentThread;
  52 import jdk.internal.vm.annotation.Hidden;
  53 import jdk.internal.vm.annotation.IntrinsicCandidate;
  54 import jdk.internal.vm.annotation.JvmtiHideEvents;
  55 import jdk.internal.vm.annotation.JvmtiMountTransition;
  56 import jdk.internal.vm.annotation.ReservedStackAccess;
  57 import sun.nio.ch.Interruptible;
  58 import static java.util.concurrent.TimeUnit.*;
  59 
  60 /**
  61  * A thread that is scheduled by the Java virtual machine rather than the operating system.
  62  */
  63 final class VirtualThread extends BaseVirtualThread {
  64     private static final Unsafe U = Unsafe.getUnsafe();
  65     private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
  66     private static final ForkJoinPool DEFAULT_SCHEDULER = createDefaultScheduler();




















  67 
  68     private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
  69     private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
  70     private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
  71     private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
  72     private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList");
  73 
  74     // scheduler and continuation
  75     private final Executor scheduler;
  76     private final Continuation cont;
  77     private final Runnable runContinuation;
  78 
  79     // virtual thread state, accessed by VM
  80     private volatile int state;
  81 
  82     /*
  83      * Virtual thread state transitions:
  84      *
  85      *      NEW -> STARTED         // Thread.start, schedule to run
  86      *  STARTED -> TERMINATED      // failed to start
  87      *  STARTED -> RUNNING         // first run
  88      *  RUNNING -> TERMINATED      // done
  89      *
  90      *  RUNNING -> PARKING         // Thread parking with LockSupport.park
  91      *  PARKING -> PARKED          // cont.yield successful, parked indefinitely
  92      *  PARKING -> PINNED          // cont.yield failed, parked indefinitely on carrier
  93      *   PARKED -> UNPARKED        // unparked, may be scheduled to continue
  94      *   PINNED -> RUNNING         // unparked, continue execution on same carrier
  95      * UNPARKED -> RUNNING         // continue execution after park
  96      *
  97      *       RUNNING -> TIMED_PARKING   // Thread parking with LockSupport.parkNanos

 133     private static final int TIMED_PINNED  = 8;     // mounted
 134     private static final int UNPARKED      = 9;     // unmounted but runnable
 135 
 136     // Thread.yield
 137     private static final int YIELDING = 10;
 138     private static final int YIELDED  = 11;         // unmounted but runnable
 139 
 140     // monitor enter
 141     private static final int BLOCKING  = 12;
 142     private static final int BLOCKED   = 13;        // unmounted
 143     private static final int UNBLOCKED = 14;        // unmounted but runnable
 144 
 145     // monitor wait/timed-wait
 146     private static final int WAITING       = 15;
 147     private static final int WAIT          = 16;    // waiting in Object.wait
 148     private static final int TIMED_WAITING = 17;
 149     private static final int TIMED_WAIT    = 18;    // waiting in timed-Object.wait
 150 
 151     private static final int TERMINATED = 99;  // final state
 152 
 153     // can be suspended from scheduling when unmounted
 154     private static final int SUSPENDED = 1 << 8;
 155 
 156     // parking permit made available by LockSupport.unpark
 157     private volatile boolean parkPermit;
 158 
 159     // blocking permit made available by unblocker thread when another thread exits monitor
 160     private volatile boolean blockPermit;
 161 
 162     // true when on the list of virtual threads waiting to be unblocked
 163     private volatile boolean onWaitingList;
 164 
 165     // next virtual thread on the list of virtual threads waiting to be unblocked
 166     private volatile VirtualThread next;
 167 
 168     // notified by Object.notify/notifyAll while waiting in Object.wait
 169     private volatile boolean notified;
 170 
 171     // true when waiting in Object.wait, false for VM internal uninterruptible Object.wait
 172     private volatile boolean interruptibleWait;
 173 
 174     // timed-wait support
 175     private byte timedWaitSeqNo;
 176 
 177     // timeout for timed-park and timed-wait, only accessed on current/carrier thread
 178     private long timeout;
 179 
 180     // timer task for timed-park and timed-wait, only accessed on current/carrier thread
 181     private Future<?> timeoutTask;
 182 
 183     // carrier thread when mounted, accessed by VM
 184     private volatile Thread carrierThread;
 185 
 186     // termination object when joining, created lazily if needed
 187     private volatile CountDownLatch termination;
 188 
 189     /**
 190      * Returns the default scheduler.
 191      */
 192     static Executor defaultScheduler() {







 193         return DEFAULT_SCHEDULER;
 194     }
 195 
 196     /**
 197      * Returns the continuation scope used for virtual threads.
 198      */
 199     static ContinuationScope continuationScope() {
 200         return VTHREAD_SCOPE;
 201     }
 202 
 203     /**
 204      * Creates a new {@code VirtualThread} to run the given task with the given
 205      * scheduler. If the given scheduler is {@code null} and the current thread
 206      * is a platform thread then the newly created virtual thread will use the
 207      * default scheduler. If given scheduler is {@code null} and the current
 208      * thread is a virtual thread then the current thread's scheduler is used.








 209      *
 210      * @param scheduler the scheduler or null

 211      * @param name thread name
 212      * @param characteristics characteristics
 213      * @param task the task to execute
 214      */
 215     VirtualThread(Executor scheduler, String name, int characteristics, Runnable task) {





 216         super(name, characteristics, /*bound*/ false);
 217         Objects.requireNonNull(task);
 218 
 219         // choose scheduler if not specified
 220         if (scheduler == null) {
 221             Thread parent = Thread.currentThread();
 222             if (parent instanceof VirtualThread vparent) {
 223                 scheduler = vparent.scheduler;
 224             } else {
 225                 scheduler = DEFAULT_SCHEDULER;
 226             }
 227         }
 228 
 229         this.scheduler = scheduler;
 230         this.cont = new VThreadContinuation(this, task);
 231         this.runContinuation = this::runContinuation;









































































 232     }
 233 
 234     /**
 235      * The continuation that a virtual thread executes.
 236      */
 237     private static class VThreadContinuation extends Continuation {
 238         VThreadContinuation(VirtualThread vthread, Runnable task) {
 239             super(VTHREAD_SCOPE, wrap(vthread, task));
 240         }
 241         @Override
 242         protected void onPinned(Continuation.Pinned reason) {
 243         }
 244         private static Runnable wrap(VirtualThread vthread, Runnable task) {
 245             return new Runnable() {
 246                 @Hidden
 247                 @JvmtiHideEvents
 248                 public void run() {
 249                     vthread.endFirstTransition();
 250                     try {
 251                         vthread.run(task);

 299             if (cont.isDone()) {
 300                 afterDone();
 301             } else {
 302                 afterYield();
 303             }
 304         }
 305     }
 306 
 307     /**
 308      * Cancel timeout task when continuing after timed-park or timed-wait.
 309      * The timeout task may be executing, or may have already completed.
 310      */
 311     private void cancelTimeoutTask() {
 312         if (timeoutTask != null) {
 313             timeoutTask.cancel(false);
 314             timeoutTask = null;
 315         }
 316     }
 317 
 318     /**
 319      * Submits the given task to the given executor. If the scheduler is a
 320      * ForkJoinPool then the task is first adapted to a ForkJoinTask.
 321      */
 322     private void submit(Executor executor, Runnable task) {
 323         if (executor instanceof ForkJoinPool pool) {
 324             pool.submit(ForkJoinTask.adapt(task));
 325         } else {
 326             executor.execute(task);
 327         }
 328     }
 329 
 330     /**
 331      * Submits the runContinuation task to the scheduler. For the default scheduler,
 332      * and calling it on a worker thread, the task will be pushed to the local queue,
 333      * otherwise it will be pushed to an external submission queue.
 334      * @param scheduler the scheduler
 335      * @param retryOnOOME true to retry indefinitely if OutOfMemoryError is thrown
 336      * @throws RejectedExecutionException
 337      */
 338     private void submitRunContinuation(Executor scheduler, boolean retryOnOOME) {
 339         boolean done = false;
 340         while (!done) {
 341             try {
 342                 // Pin the continuation to prevent the virtual thread from unmounting
 343                 // when submitting a task. For the default scheduler this ensures that
 344                 // the carrier doesn't change when pushing a task. For other schedulers
 345                 // it avoids deadlock that could arise due to carriers and virtual
 346                 // threads contending for a lock.
 347                 if (currentThread().isVirtual()) {
 348                     Continuation.pin();
 349                     try {
 350                         submit(scheduler, runContinuation);
 351                     } finally {
 352                         Continuation.unpin();
 353                     }
 354                 } else {
 355                     submit(scheduler, runContinuation);
 356                 }
 357                 done = true;
 358             } catch (RejectedExecutionException ree) {
 359                 submitFailed(ree);
 360                 throw ree;
 361             } catch (OutOfMemoryError e) {
 362                 if (retryOnOOME) {
 363                     U.park(false, 100_000_000); // 100ms
 364                 } else {
 365                     throw e;
 366                 }
 367             }
 368         }
 369     }
 370 
 371     /**
 372      * Submits the runContinuation task to the given scheduler as an external submit.
 373      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 374      * @throws RejectedExecutionException
 375      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 376      */
 377     private void externalSubmitRunContinuation(ForkJoinPool pool) {
 378         assert Thread.currentThread() instanceof CarrierThread;
 379         try {
 380             pool.externalSubmit(ForkJoinTask.adapt(runContinuation));
 381         } catch (RejectedExecutionException ree) {
 382             submitFailed(ree);
 383             throw ree;
 384         } catch (OutOfMemoryError e) {
 385             submitRunContinuation(pool, true);
 386         }
 387     }
 388 
 389     /**
 390      * Submits the runContinuation task to the scheduler. For the default scheduler,
 391      * and calling it on a worker thread, the task will be pushed to the local queue,
 392      * otherwise it will be pushed to an external submission queue.
 393      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 394      * @throws RejectedExecutionException
 395      */
 396     private void submitRunContinuation() {
 397         submitRunContinuation(scheduler, true);
 398     }
 399 
 400     /**
 401      * Lazy submit the runContinuation task if invoked on a carrier thread and its local
 402      * queue is empty. If not empty, or invoked by another thread, then this method works
 403      * like submitRunContinuation and just submits the task to the scheduler.
 404      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 405      * @throws RejectedExecutionException
 406      * @see ForkJoinPool#lazySubmit(ForkJoinTask)
 407      */
 408     private void lazySubmitRunContinuation() {

 409         if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
 410             ForkJoinPool pool = ct.getPool();
 411             try {
 412                 pool.lazySubmit(ForkJoinTask.adapt(runContinuation));
 413             } catch (RejectedExecutionException ree) {
 414                 submitFailed(ree);
 415                 throw ree;
 416             } catch (OutOfMemoryError e) {
 417                 submitRunContinuation();
 418             }
 419         } else {
 420             submitRunContinuation();
 421         }
 422     }
 423 
 424     /**
 425      * Submits the runContinuation task to the scheduler. For the default scheduler, and
 426      * calling it a virtual thread that uses the default scheduler, the task will be
 427      * pushed to an external submission queue. This method may throw OutOfMemoryError.

 428      * @throws RejectedExecutionException
 429      * @throws OutOfMemoryError
 430      */
 431     private void externalSubmitRunContinuationOrThrow() {
 432         if (scheduler == DEFAULT_SCHEDULER && currentCarrierThread() instanceof CarrierThread ct) {

 433             try {
 434                 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
 435             } catch (RejectedExecutionException ree) {
 436                 submitFailed(ree);
 437                 throw ree;


 438             }
 439         } else {
 440             submitRunContinuation(scheduler, false);




































 441         }
 442     }
 443 
 444     /**
 445      * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
 446      */
 447     private void submitFailed(RejectedExecutionException ree) {
 448         var event = new VirtualThreadSubmitFailedEvent();
 449         if (event.isEnabled()) {
 450             event.javaThreadId = threadId();
 451             event.exceptionMessage = ree.getMessage();
 452             event.commit();
 453         }
 454     }
 455 
 456     /**
 457      * Runs a task in the context of this virtual thread.
 458      */
 459     private void run(Runnable task) {
 460         assert Thread.currentThread() == this && state == RUNNING;

 577                 long timeout = this.timeout;
 578                 assert timeout > 0;
 579                 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS);
 580                 setState(newState = TIMED_PARKED);
 581             }
 582 
 583             // may have been unparked while parking
 584             if (parkPermit && compareAndSetState(newState, UNPARKED)) {
 585                 // lazy submit if local queue is empty
 586                 lazySubmitRunContinuation();
 587             }
 588             return;
 589         }
 590 
 591         // Thread.yield
 592         if (s == YIELDING) {
 593             setState(YIELDED);
 594 
 595             // external submit if there are no tasks in the local task queue
 596             if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
 597                 externalSubmitRunContinuation(ct.getPool());
 598             } else {
 599                 submitRunContinuation();
 600             }
 601             return;
 602         }
 603 
 604         // blocking on monitorenter
 605         if (s == BLOCKING) {
 606             setState(BLOCKED);
 607 
 608             // may have been unblocked while blocking
 609             if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
 610                 // lazy submit if local queue is empty
 611                 lazySubmitRunContinuation();
 612             }
 613             return;
 614         }
 615 
 616         // Object.wait
 617         if (s == WAITING || s == TIMED_WAITING) {

 734     @Override
 735     public void run() {
 736         // do nothing
 737     }
 738 
 739     /**
 740      * Parks until unparked or interrupted. If already unparked then the parking
 741      * permit is consumed and this method completes immediately (meaning it doesn't
 742      * yield). It also completes immediately if the interrupted status is set.
 743      */
 744     @Override
 745     void park() {
 746         assert Thread.currentThread() == this;
 747 
 748         // complete immediately if parking permit available or interrupted
 749         if (getAndSetParkPermit(false) || interrupted)
 750             return;
 751 
 752         // park the thread
 753         boolean yielded = false;

 754         setState(PARKING);
 755         try {
 756             yielded = yieldContinuation();
 757         } catch (OutOfMemoryError e) {
 758             // park on carrier
 759         } finally {
 760             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 761             if (!yielded) {


 762                 assert state() == PARKING;
 763                 setState(RUNNING);
 764             }
 765         }
 766 
 767         // park on the carrier thread when pinned
 768         if (!yielded) {
 769             parkOnCarrierThread(false, 0);
 770         }
 771     }
 772 
 773     /**
 774      * Parks up to the given waiting time or until unparked or interrupted.
 775      * If already unparked then the parking permit is consumed and this method
 776      * completes immediately (meaning it doesn't yield). It also completes immediately
 777      * if the interrupted status is set or the waiting time is {@code <= 0}.
 778      *
 779      * @param nanos the maximum number of nanoseconds to wait.
 780      */
 781     @Override
 782     void parkNanos(long nanos) {
 783         assert Thread.currentThread() == this;
 784 
 785         // complete immediately if parking permit available or interrupted
 786         if (getAndSetParkPermit(false) || interrupted)
 787             return;
 788 
 789         // park the thread for the waiting time
 790         if (nanos > 0) {
 791             long startTime = System.nanoTime();
 792 
 793             // park the thread, afterYield will schedule the thread to unpark
 794             boolean yielded = false;

 795             timeout = nanos;
 796             setState(TIMED_PARKING);
 797             try {
 798                 yielded = yieldContinuation();
 799             } catch (OutOfMemoryError e) {
 800                 // park on carrier
 801             } finally {
 802                 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 803                 if (!yielded) {


 804                     assert state() == TIMED_PARKING;
 805                     setState(RUNNING);
 806                 }
 807             }
 808 
 809             // park on carrier thread for remaining time when pinned (or OOME)
 810             if (!yielded) {
 811                 long remainingNanos = nanos - (System.nanoTime() - startTime);
 812                 parkOnCarrierThread(true, remainingNanos);
 813             }
 814         }
 815     }
 816 
 817     /**
 818      * Parks the current carrier thread up to the given waiting time or until
 819      * unparked or interrupted. If the virtual thread is interrupted then the
 820      * interrupted status will be propagated to the carrier thread.
 821      * @param timed true for a timed park, false for untimed
 822      * @param nanos the waiting time in nanoseconds
 823      */

 902     /**
 903      * Invoked by FJP worker thread or STPE thread when park timeout expires.
 904      */
 905     private void parkTimeoutExpired() {
 906         assert !VirtualThread.currentThread().isVirtual();
 907         if (!getAndSetParkPermit(true)
 908                 && (state() == TIMED_PARKED)
 909                 && compareAndSetState(TIMED_PARKED, UNPARKED)) {
 910             lazySubmitRunContinuation();
 911         }
 912     }
 913 
 914     /**
 915      * Invoked by FJP worker thread or STPE thread when wait timeout expires.
 916      * If the virtual thread is in timed-wait then this method will unblock the thread
 917      * and submit its task so that it continues and attempts to reenter the monitor.
 918      * This method does nothing if the thread has been woken by notify or interrupt.
 919      */
 920     private void waitTimeoutExpired(byte seqNo) {
 921         assert !Thread.currentThread().isVirtual();
 922         for (;;) {
 923             boolean unblocked = false;
 924             synchronized (timedWaitLock()) {
 925                 if (seqNo != timedWaitSeqNo) {
 926                     // this timeout task is for a past timed-wait
 927                     return;
 928                 }
 929                 int s = state();
 930                 if (s == TIMED_WAIT) {
 931                     unblocked = compareAndSetState(TIMED_WAIT, UNBLOCKED);
 932                 } else if (s != (TIMED_WAIT | SUSPENDED)) {
 933                     // notified or interrupted, no longer waiting
 934                     return;
 935                 }
 936             }
 937             if (unblocked) {
 938                 lazySubmitRunContinuation();
 939                 return;
 940             }
 941             // need to retry when thread is suspended in time-wait
 942             Thread.yield();
 943         }
 944     }
 945 
 946     /**
 947      * Attempts to yield the current virtual thread (Thread.yield).
 948      */
 949     void tryYield() {
 950         assert Thread.currentThread() == this;
 951         setState(YIELDING);
 952         boolean yielded = false;
 953         try {
 954             yielded = yieldContinuation();  // may throw
 955         } finally {
 956             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 957             if (!yielded) {
 958                 assert state() == YIELDING;
 959                 setState(RUNNING);
 960             }
 961         }
 962     }

1091     @Override
1092     boolean getAndClearInterrupt() {
1093         assert Thread.currentThread() == this;
1094         boolean oldValue = interrupted;
1095         if (oldValue) {
1096             disableSuspendAndPreempt();
1097             try {
1098                 synchronized (interruptLock) {
1099                     interrupted = false;
1100                     carrierThread.clearInterrupt();
1101                 }
1102             } finally {
1103                 enableSuspendAndPreempt();
1104             }
1105         }
1106         return oldValue;
1107     }
1108 
1109     @Override
1110     Thread.State threadState() {
1111         int s = state();
1112         switch (s & ~SUSPENDED) {
1113             case NEW:
1114                 return Thread.State.NEW;
1115             case STARTED:
1116                 // return NEW if thread container not yet set
1117                 if (threadContainer() == null) {
1118                     return Thread.State.NEW;
1119                 } else {
1120                     return Thread.State.RUNNABLE;
1121                 }
1122             case UNPARKED:
1123             case UNBLOCKED:
1124             case YIELDED:
1125                 // runnable, not mounted
1126                 return Thread.State.RUNNABLE;
1127             case RUNNING:
1128                 // if mounted then return state of carrier thread
1129                 if (Thread.currentThread() != this) {
1130                     disableSuspendAndPreempt();
1131                     try {
1132                         synchronized (carrierThreadAccessLock()) {

1160             case BLOCKED:
1161                 return Thread.State.BLOCKED;
1162             case TERMINATED:
1163                 return Thread.State.TERMINATED;
1164             default:
1165                 throw new InternalError();
1166         }
1167     }
1168 
1169     @Override
1170     boolean alive() {
1171         int s = state;
1172         return (s != NEW && s != TERMINATED);
1173     }
1174 
1175     @Override
1176     boolean isTerminated() {
1177         return (state == TERMINATED);
1178     }
1179 
1180     @Override
1181     StackTraceElement[] asyncGetStackTrace() {
1182         StackTraceElement[] stackTrace;
1183         do {
1184             stackTrace = (carrierThread != null)
1185                     ? super.asyncGetStackTrace()  // mounted
1186                     : tryGetStackTrace();         // unmounted
1187             if (stackTrace == null) {
1188                 Thread.yield();
1189             }
1190         } while (stackTrace == null);
1191         return stackTrace;
1192     }
1193 
1194     /**
1195      * Returns the stack trace for this virtual thread if it is unmounted.
1196      * Returns null if the thread is mounted or in transition.
1197      */
1198     private StackTraceElement[] tryGetStackTrace() {
1199         int initialState = state() & ~SUSPENDED;
1200         switch (initialState) {
1201             case NEW, STARTED, TERMINATED -> {
1202                 return new StackTraceElement[0];  // unmounted, empty stack
1203             }
1204             case RUNNING, PINNED, TIMED_PINNED -> {
1205                 return null;   // mounted
1206             }
1207             case PARKED, TIMED_PARKED, BLOCKED, WAIT, TIMED_WAIT -> {
1208                 // unmounted, not runnable
1209             }
1210             case UNPARKED, UNBLOCKED, YIELDED -> {
1211                 // unmounted, runnable
1212             }
1213             case PARKING, TIMED_PARKING, BLOCKING, YIELDING, WAITING, TIMED_WAITING -> {
1214                 return null;  // in transition
1215             }
1216             default -> throw new InternalError("" + initialState);
1217         }
1218 
1219         // thread is unmounted, prevent it from continuing
1220         int suspendedState = initialState | SUSPENDED;
1221         if (!compareAndSetState(initialState, suspendedState)) {
1222             return null;
1223         }
1224 
1225         // get stack trace and restore state
1226         StackTraceElement[] stack;
1227         try {
1228             stack = cont.getStackTrace();
1229         } finally {
1230             assert state == suspendedState;
1231             setState(initialState);
1232         }
1233         boolean resubmit = switch (initialState) {
1234             case UNPARKED, UNBLOCKED, YIELDED -> {
1235                 // resubmit as task may have run while suspended
1236                 yield true;
1237             }
1238             case PARKED, TIMED_PARKED -> {
1239                 // resubmit if unparked while suspended
1240                 yield parkPermit && compareAndSetState(initialState, UNPARKED);
1241             }
1242             case BLOCKED -> {
1243                 // resubmit if unblocked while suspended
1244                 yield blockPermit && compareAndSetState(BLOCKED, UNBLOCKED);
1245             }
1246             case WAIT, TIMED_WAIT -> {
1247                 // resubmit if notified or interrupted while waiting (Object.wait)
1248                 // waitTimeoutExpired will retry if the timed expired when suspended
1249                 yield (notified || interrupted) && compareAndSetState(initialState, UNBLOCKED);
1250             }
1251             default -> throw new InternalError();
1252         };
1253         if (resubmit) {
1254             submitRunContinuation();
1255         }
1256         return stack;
1257     }
1258 
1259     @Override
1260     public String toString() {
1261         StringBuilder sb = new StringBuilder("VirtualThread[#");
1262         sb.append(threadId());
1263         String name = getName();
1264         if (!name.isEmpty()) {
1265             sb.append(",");
1266             sb.append(name);
1267         }
1268         sb.append("]/");
1269 
1270         // add the carrier state and thread name when mounted
1271         boolean mounted;
1272         if (Thread.currentThread() == this) {
1273             mounted = appendCarrierInfo(sb);
1274         } else {
1275             disableSuspendAndPreempt();
1276             try {
1277                 synchronized (carrierThreadAccessLock()) {
1278                     mounted = appendCarrierInfo(sb);

1424     @JvmtiMountTransition
1425     private native void startFinalTransition();
1426 
1427     @IntrinsicCandidate
1428     @JvmtiMountTransition
1429     private native void startTransition(boolean is_mount);
1430 
1431     @IntrinsicCandidate
1432     @JvmtiMountTransition
1433     private native void endTransition(boolean is_mount);
1434 
1435     @IntrinsicCandidate
1436     private static native void notifyJvmtiDisableSuspend(boolean enter);
1437 
1438     private static native void registerNatives();
1439     static {
1440         registerNatives();
1441 
1442         // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1443         var group = Thread.virtualThreadGroup();


































1444     }
1445 
1446     /**
1447      * Creates the default ForkJoinPool scheduler.

1448      */
1449     private static ForkJoinPool createDefaultScheduler() {
1450         ForkJoinWorkerThreadFactory factory = pool -> new CarrierThread(pool);
1451         int parallelism, maxPoolSize, minRunnable;
1452         String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1453         String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1454         String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1455         if (parallelismValue != null) {
1456             parallelism = Integer.parseInt(parallelismValue);
1457         } else {
1458             parallelism = Runtime.getRuntime().availableProcessors();
1459         }
1460         if (maxPoolSizeValue != null) {
1461             maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1462             parallelism = Integer.min(parallelism, maxPoolSize);
1463         } else {
1464             maxPoolSize = Integer.max(parallelism, 256);
1465         }
1466         if (minRunnableValue != null) {
1467             minRunnable = Integer.parseInt(minRunnableValue);
1468         } else {
1469             minRunnable = Integer.max(parallelism / 2, 1);
1470         }
1471         Thread.UncaughtExceptionHandler handler = (t, e) -> { };
1472         boolean asyncMode = true; // FIFO
1473         return new ForkJoinPool(parallelism, factory, handler, asyncMode,
1474                      0, maxPoolSize, minRunnable, pool -> true, 30, SECONDS);



























































1475     }
1476 
1477     /**
1478      * Schedule a runnable task to run after a delay.
1479      */
1480     private Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1481         if (scheduler instanceof ForkJoinPool pool) {
1482             return pool.schedule(command, delay, unit);
1483         } else {
1484             return DelayedTaskSchedulers.schedule(command, delay, unit);
1485         }
1486     }
1487 
1488     /**
1489      * Supports scheduling a runnable task to run after a delay. It uses a number
1490      * of ScheduledThreadPoolExecutor instances to reduce contention on the delayed
1491      * work queue used. This class is used when using a custom scheduler.
1492      */
1493     private static class DelayedTaskSchedulers {
1494         private static final ScheduledExecutorService[] INSTANCE = createDelayedTaskSchedulers();
1495 
1496         static Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1497             long tid = Thread.currentThread().threadId();
1498             int index = (int) tid & (INSTANCE.length - 1);
1499             return INSTANCE[index].schedule(command, delay, unit);
1500         }
1501 
1502         private static ScheduledExecutorService[] createDelayedTaskSchedulers() {

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

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

  35 import java.util.concurrent.ForkJoinTask;
  36 import java.util.concurrent.Future;
  37 import java.util.concurrent.RejectedExecutionException;
  38 import java.util.concurrent.ScheduledExecutorService;
  39 import java.util.concurrent.ScheduledThreadPoolExecutor;
  40 import java.util.concurrent.TimeUnit;
  41 import jdk.internal.event.VirtualThreadEndEvent;
  42 import jdk.internal.event.VirtualThreadParkEvent;
  43 import jdk.internal.event.VirtualThreadStartEvent;
  44 import jdk.internal.event.VirtualThreadSubmitFailedEvent;
  45 import jdk.internal.invoke.MhUtil;
  46 import jdk.internal.misc.CarrierThread;
  47 import jdk.internal.misc.InnocuousThread;
  48 import jdk.internal.misc.Unsafe;
  49 import jdk.internal.vm.Continuation;
  50 import jdk.internal.vm.ContinuationScope;
  51 import jdk.internal.vm.StackableScope;
  52 import jdk.internal.vm.ThreadContainer;
  53 import jdk.internal.vm.ThreadContainers;
  54 import jdk.internal.vm.annotation.ChangesCurrentThread;
  55 import jdk.internal.vm.annotation.Hidden;
  56 import jdk.internal.vm.annotation.IntrinsicCandidate;
  57 import jdk.internal.vm.annotation.JvmtiHideEvents;
  58 import jdk.internal.vm.annotation.JvmtiMountTransition;
  59 import jdk.internal.vm.annotation.ReservedStackAccess;
  60 import sun.nio.ch.Interruptible;
  61 import static java.util.concurrent.TimeUnit.*;
  62 
  63 /**
  64  * A thread that is scheduled by the Java virtual machine rather than the operating system.
  65  */
  66 final class VirtualThread extends BaseVirtualThread {
  67     private static final Unsafe U = Unsafe.getUnsafe();
  68     private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
  69 
  70     private static final BuiltinScheduler BUILTIN_SCHEDULER;
  71     private static final VirtualThreadScheduler DEFAULT_SCHEDULER;
  72     private static final VirtualThreadScheduler EXTERNAL_VIEW;
  73     static {
  74         // experimental
  75         String propValue = System.getProperty("jdk.virtualThreadScheduler.implClass");
  76         if (propValue != null) {
  77             BuiltinScheduler builtinScheduler = createBuiltinScheduler(true);
  78             VirtualThreadScheduler externalView = builtinScheduler.createExternalView();
  79             VirtualThreadScheduler defaultScheduler = loadCustomScheduler(externalView, propValue);
  80             BUILTIN_SCHEDULER = builtinScheduler;
  81             DEFAULT_SCHEDULER = defaultScheduler;
  82             EXTERNAL_VIEW = externalView;
  83         } else {
  84             var builtinScheduler = createBuiltinScheduler(false);
  85             BUILTIN_SCHEDULER = builtinScheduler;
  86             DEFAULT_SCHEDULER = builtinScheduler;
  87             EXTERNAL_VIEW = builtinScheduler.createExternalView();
  88         }
  89     }
  90 
  91     private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
  92     private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
  93     private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
  94     private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
  95     private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList");
  96 
  97     // scheduler and continuation
  98     private final VirtualThreadScheduler scheduler;
  99     private final Continuation cont;
 100     private final VirtualThreadTask runContinuation;
 101 
 102     // virtual thread state, accessed by VM
 103     private volatile int state;
 104 
 105     /*
 106      * Virtual thread state transitions:
 107      *
 108      *      NEW -> STARTED         // Thread.start, schedule to run
 109      *  STARTED -> TERMINATED      // failed to start
 110      *  STARTED -> RUNNING         // first run
 111      *  RUNNING -> TERMINATED      // done
 112      *
 113      *  RUNNING -> PARKING         // Thread parking with LockSupport.park
 114      *  PARKING -> PARKED          // cont.yield successful, parked indefinitely
 115      *  PARKING -> PINNED          // cont.yield failed, parked indefinitely on carrier
 116      *   PARKED -> UNPARKED        // unparked, may be scheduled to continue
 117      *   PINNED -> RUNNING         // unparked, continue execution on same carrier
 118      * UNPARKED -> RUNNING         // continue execution after park
 119      *
 120      *       RUNNING -> TIMED_PARKING   // Thread parking with LockSupport.parkNanos

 156     private static final int TIMED_PINNED  = 8;     // mounted
 157     private static final int UNPARKED      = 9;     // unmounted but runnable
 158 
 159     // Thread.yield
 160     private static final int YIELDING = 10;
 161     private static final int YIELDED  = 11;         // unmounted but runnable
 162 
 163     // monitor enter
 164     private static final int BLOCKING  = 12;
 165     private static final int BLOCKED   = 13;        // unmounted
 166     private static final int UNBLOCKED = 14;        // unmounted but runnable
 167 
 168     // monitor wait/timed-wait
 169     private static final int WAITING       = 15;
 170     private static final int WAIT          = 16;    // waiting in Object.wait
 171     private static final int TIMED_WAITING = 17;
 172     private static final int TIMED_WAIT    = 18;    // waiting in timed-Object.wait
 173 
 174     private static final int TERMINATED = 99;  // final state
 175 



 176     // parking permit made available by LockSupport.unpark
 177     private volatile boolean parkPermit;
 178 
 179     // blocking permit made available by unblocker thread when another thread exits monitor
 180     private volatile boolean blockPermit;
 181 
 182     // true when on the list of virtual threads waiting to be unblocked
 183     private volatile boolean onWaitingList;
 184 
 185     // next virtual thread on the list of virtual threads waiting to be unblocked
 186     private volatile VirtualThread next;
 187 
 188     // notified by Object.notify/notifyAll while waiting in Object.wait
 189     private volatile boolean notified;
 190 
 191     // true when waiting in Object.wait, false for VM internal uninterruptible Object.wait
 192     private volatile boolean interruptibleWait;
 193 
 194     // timed-wait support
 195     private byte timedWaitSeqNo;
 196 
 197     // timeout for timed-park and timed-wait, only accessed on current/carrier thread
 198     private long timeout;
 199 
 200     // timer task for timed-park and timed-wait, only accessed on current/carrier thread
 201     private Future<?> timeoutTask;
 202 
 203     // carrier thread when mounted, accessed by VM
 204     private volatile Thread carrierThread;
 205 
 206     // termination object when joining, created lazily if needed
 207     private volatile CountDownLatch termination;
 208 
 209     /**
 210      * Return the built-in scheduler.
 211      */
 212     static VirtualThreadScheduler builtinScheduler() {
 213         return BUILTIN_SCHEDULER;
 214     }
 215 
 216     /**
 217      * Returns the default scheduler, usually the same as the built-in scheduler.
 218      */
 219     static VirtualThreadScheduler defaultScheduler() {
 220         return DEFAULT_SCHEDULER;
 221     }
 222 
 223     /**
 224      * Returns the continuation scope used for virtual threads.
 225      */
 226     static ContinuationScope continuationScope() {
 227         return VTHREAD_SCOPE;
 228     }
 229 
 230     /**
 231      * Return the scheduler for this thread.
 232      * @param trusted true if caller is trusted, false if not trusted
 233      */
 234     VirtualThreadScheduler scheduler(boolean trusted) {
 235         if (scheduler == BUILTIN_SCHEDULER && !trusted) {
 236             return EXTERNAL_VIEW;
 237         } else {
 238             return scheduler;
 239         }
 240     }
 241 
 242     /**
 243      * Creates a new {@code VirtualThread} to run the given task with the given scheduler.
 244      *
 245      * @param scheduler the scheduler or null for default scheduler
 246      * @param preferredCarrier the preferred carrier or null
 247      * @param name thread name
 248      * @param characteristics characteristics
 249      * @param task the task to execute
 250      */
 251     VirtualThread(VirtualThreadScheduler scheduler,
 252                   Thread preferredCarrier,
 253                   String name,
 254                   int characteristics,
 255                   Runnable task,
 256                   Object att) {
 257         super(name, characteristics, /*bound*/ false);
 258         Objects.requireNonNull(task);
 259 
 260         // use default scheduler if not provided
 261         if (scheduler == null) {
 262             scheduler = DEFAULT_SCHEDULER;
 263         } else if (scheduler == EXTERNAL_VIEW) {
 264             throw new UnsupportedOperationException();



 265         }

 266         this.scheduler = scheduler;
 267         this.cont = new VThreadContinuation(this, task);
 268 
 269         if (scheduler == BUILTIN_SCHEDULER) {
 270             this.runContinuation = new BuiltinSchedulerTask(this);
 271         } else {
 272             this.runContinuation = new CustomSchedulerTask(this, preferredCarrier, att);
 273         }
 274     }
 275 
 276     /**
 277      * The task to execute when using the built-in scheduler.
 278      */
 279     static final class BuiltinSchedulerTask implements VirtualThreadTask {
 280         private final VirtualThread vthread;
 281         BuiltinSchedulerTask(VirtualThread vthread) {
 282             this.vthread = vthread;
 283         }
 284         @Override
 285         public Thread thread() {
 286             return vthread;
 287         }
 288         @Override
 289         public void run() {
 290             vthread.runContinuation();;
 291         }
 292         @Override
 293         public Thread preferredCarrier() {
 294             throw new UnsupportedOperationException();
 295         }
 296         @Override
 297         public Object attach(Object att) {
 298             throw new UnsupportedOperationException();
 299         }
 300         @Override
 301         public Object attachment() {
 302             throw new UnsupportedOperationException();
 303         }
 304     }
 305 
 306     /**
 307      * The task to execute when using a custom scheduler.
 308      */
 309     static final class CustomSchedulerTask implements VirtualThreadTask {
 310         private static final VarHandle ATT =
 311                 MhUtil.findVarHandle(MethodHandles.lookup(), "att", Object.class);
 312         private final VirtualThread vthread;
 313         private final Thread preferredCarrier;
 314         private volatile Object att;
 315         CustomSchedulerTask(VirtualThread vthread, Thread preferredCarrier, Object att) {
 316             this.vthread = vthread;
 317             this.preferredCarrier = preferredCarrier;
 318             if (att != null) {
 319                 this.att = att;
 320             }
 321         }
 322         @Override
 323         public Thread thread() {
 324             return vthread;
 325         }
 326         @Override
 327         public void run() {
 328             vthread.runContinuation();;
 329         }
 330         @Override
 331         public Thread preferredCarrier() {
 332             return preferredCarrier;
 333         }
 334         @Override
 335         public Object attach(Object att) {
 336             return ATT.getAndSet(this, att);
 337         }
 338         @Override
 339         public Object attachment() {
 340             return att;
 341         }
 342     }
 343 
 344     /**
 345      * The continuation that a virtual thread executes.
 346      */
 347     private static class VThreadContinuation extends Continuation {
 348         VThreadContinuation(VirtualThread vthread, Runnable task) {
 349             super(VTHREAD_SCOPE, wrap(vthread, task));
 350         }
 351         @Override
 352         protected void onPinned(Continuation.Pinned reason) {
 353         }
 354         private static Runnable wrap(VirtualThread vthread, Runnable task) {
 355             return new Runnable() {
 356                 @Hidden
 357                 @JvmtiHideEvents
 358                 public void run() {
 359                     vthread.endFirstTransition();
 360                     try {
 361                         vthread.run(task);

 409             if (cont.isDone()) {
 410                 afterDone();
 411             } else {
 412                 afterYield();
 413             }
 414         }
 415     }
 416 
 417     /**
 418      * Cancel timeout task when continuing after timed-park or timed-wait.
 419      * The timeout task may be executing, or may have already completed.
 420      */
 421     private void cancelTimeoutTask() {
 422         if (timeoutTask != null) {
 423             timeoutTask.cancel(false);
 424             timeoutTask = null;
 425         }
 426     }
 427 
 428     /**
 429      * Submits the runContinuation task to the scheduler. For the built-in scheduler,
 430      * the task will be pushed to the local queue if possible, otherwise it will be
 431      * pushed to an external submission queue.













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


















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

 490             try {
 491                 ct.getPool().lazySubmit(ForkJoinTask.adapt(runContinuation));
 492             } catch (RejectedExecutionException ree) {
 493                 submitFailed(ree);
 494                 throw ree;
 495             } catch (OutOfMemoryError e) {
 496                 submitRunContinuation();
 497             }
 498         } else {
 499             submitRunContinuation();
 500         }
 501     }
 502 
 503     /**
 504      * Invoked from a carrier thread to externally submit the runContinuation task to the
 505      * scheduler. If invoked by a thread for a custom scheduler, then it just submits the
 506      * task to the scheduler.
 507      * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
 508      * @throws RejectedExecutionException
 509      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 510      */
 511     private void externalSubmitRunContinuation() {
 512         assert !currentThread().isVirtual();
 513         if (currentThread() instanceof CarrierThread ct) {
 514             try {
 515                 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
 516             } catch (RejectedExecutionException ree) {
 517                 submitFailed(ree);
 518                 throw ree;
 519             } catch (OutOfMemoryError e) {
 520                 submitRunContinuation();
 521             }
 522         } else {
 523             submitRunContinuation();
 524         }
 525     }
 526 
 527     /**
 528      * Invoked from Thread.start to externally submit the runContinuation task to the
 529      * scheduler. If this virtual thread is scheduled by the built-in scheduler,
 530      * and this method is called from a virtual thread scheduled by the built-in
 531      * scheduler, then it uses externalSubmit to ensure that the task is pushed to an
 532      * external submission queue rather than the local queue.
 533      * @throws RejectedExecutionException
 534      * @throws OutOfMemoryError
 535      * @see ForkJoinPool#externalSubmit(ForkJoinTask)
 536      */
 537     private void externalSubmitRunContinuationOrThrow() {
 538         try {
 539             if (currentThread().isVirtual()) {
 540                 // Pin the continuation to prevent the virtual thread from unmounting
 541                 // when submitting a task. This avoids deadlock that could arise due to
 542                 // carriers and virtual threads contending for a lock.
 543                 Continuation.pin();
 544                 try {
 545                     if (scheduler == BUILTIN_SCHEDULER
 546                             && currentCarrierThread() instanceof CarrierThread ct) {
 547                         ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
 548                     } else {
 549                         scheduler.onStart(runContinuation);
 550                     }
 551                 } finally {
 552                     Continuation.unpin();
 553                 }
 554             } else {
 555                 scheduler.onStart(runContinuation);
 556             }
 557         } catch (RejectedExecutionException ree) {
 558             submitFailed(ree);
 559             throw ree;
 560         }
 561     }
 562 
 563     /**
 564      * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
 565      */
 566     private void submitFailed(RejectedExecutionException ree) {
 567         var event = new VirtualThreadSubmitFailedEvent();
 568         if (event.isEnabled()) {
 569             event.javaThreadId = threadId();
 570             event.exceptionMessage = ree.getMessage();
 571             event.commit();
 572         }
 573     }
 574 
 575     /**
 576      * Runs a task in the context of this virtual thread.
 577      */
 578     private void run(Runnable task) {
 579         assert Thread.currentThread() == this && state == RUNNING;

 696                 long timeout = this.timeout;
 697                 assert timeout > 0;
 698                 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS);
 699                 setState(newState = TIMED_PARKED);
 700             }
 701 
 702             // may have been unparked while parking
 703             if (parkPermit && compareAndSetState(newState, UNPARKED)) {
 704                 // lazy submit if local queue is empty
 705                 lazySubmitRunContinuation();
 706             }
 707             return;
 708         }
 709 
 710         // Thread.yield
 711         if (s == YIELDING) {
 712             setState(YIELDED);
 713 
 714             // external submit if there are no tasks in the local task queue
 715             if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
 716                 externalSubmitRunContinuation();
 717             } else {
 718                 submitRunContinuation();
 719             }
 720             return;
 721         }
 722 
 723         // blocking on monitorenter
 724         if (s == BLOCKING) {
 725             setState(BLOCKED);
 726 
 727             // may have been unblocked while blocking
 728             if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
 729                 // lazy submit if local queue is empty
 730                 lazySubmitRunContinuation();
 731             }
 732             return;
 733         }
 734 
 735         // Object.wait
 736         if (s == WAITING || s == TIMED_WAITING) {

 853     @Override
 854     public void run() {
 855         // do nothing
 856     }
 857 
 858     /**
 859      * Parks until unparked or interrupted. If already unparked then the parking
 860      * permit is consumed and this method completes immediately (meaning it doesn't
 861      * yield). It also completes immediately if the interrupted status is set.
 862      */
 863     @Override
 864     void park() {
 865         assert Thread.currentThread() == this;
 866 
 867         // complete immediately if parking permit available or interrupted
 868         if (getAndSetParkPermit(false) || interrupted)
 869             return;
 870 
 871         // park the thread
 872         boolean yielded = false;
 873         long eventStartTime = VirtualThreadParkEvent.eventStartTime();
 874         setState(PARKING);
 875         try {
 876             yielded = yieldContinuation();
 877         } catch (OutOfMemoryError e) {
 878             // park on carrier
 879         } finally {
 880             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 881             if (yielded) {
 882                 VirtualThreadParkEvent.offer(eventStartTime, Long.MIN_VALUE);
 883             } else {
 884                 assert state() == PARKING;
 885                 setState(RUNNING);
 886             }
 887         }
 888 
 889         // park on the carrier thread when pinned
 890         if (!yielded) {
 891             parkOnCarrierThread(false, 0);
 892         }
 893     }
 894 
 895     /**
 896      * Parks up to the given waiting time or until unparked or interrupted.
 897      * If already unparked then the parking permit is consumed and this method
 898      * completes immediately (meaning it doesn't yield). It also completes immediately
 899      * if the interrupted status is set or the waiting time is {@code <= 0}.
 900      *
 901      * @param nanos the maximum number of nanoseconds to wait.
 902      */
 903     @Override
 904     void parkNanos(long nanos) {
 905         assert Thread.currentThread() == this;
 906 
 907         // complete immediately if parking permit available or interrupted
 908         if (getAndSetParkPermit(false) || interrupted)
 909             return;
 910 
 911         // park the thread for the waiting time
 912         if (nanos > 0) {
 913             long startTime = System.nanoTime();
 914 
 915             // park the thread, afterYield will schedule the thread to unpark
 916             boolean yielded = false;
 917             long eventStartTime = VirtualThreadParkEvent.eventStartTime();
 918             timeout = nanos;
 919             setState(TIMED_PARKING);
 920             try {
 921                 yielded = yieldContinuation();
 922             } catch (OutOfMemoryError e) {
 923                 // park on carrier
 924             } finally {
 925                 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
 926                 if (yielded) {
 927                     VirtualThreadParkEvent.offer(eventStartTime, nanos);
 928                 } else {
 929                     assert state() == TIMED_PARKING;
 930                     setState(RUNNING);
 931                 }
 932             }
 933 
 934             // park on carrier thread for remaining time when pinned (or OOME)
 935             if (!yielded) {
 936                 long remainingNanos = nanos - (System.nanoTime() - startTime);
 937                 parkOnCarrierThread(true, remainingNanos);
 938             }
 939         }
 940     }
 941 
 942     /**
 943      * Parks the current carrier thread up to the given waiting time or until
 944      * unparked or interrupted. If the virtual thread is interrupted then the
 945      * interrupted status will be propagated to the carrier thread.
 946      * @param timed true for a timed park, false for untimed
 947      * @param nanos the waiting time in nanoseconds
 948      */

1027     /**
1028      * Invoked by FJP worker thread or STPE thread when park timeout expires.
1029      */
1030     private void parkTimeoutExpired() {
1031         assert !VirtualThread.currentThread().isVirtual();
1032         if (!getAndSetParkPermit(true)
1033                 && (state() == TIMED_PARKED)
1034                 && compareAndSetState(TIMED_PARKED, UNPARKED)) {
1035             lazySubmitRunContinuation();
1036         }
1037     }
1038 
1039     /**
1040      * Invoked by FJP worker thread or STPE thread when wait timeout expires.
1041      * If the virtual thread is in timed-wait then this method will unblock the thread
1042      * and submit its task so that it continues and attempts to reenter the monitor.
1043      * This method does nothing if the thread has been woken by notify or interrupt.
1044      */
1045     private void waitTimeoutExpired(byte seqNo) {
1046         assert !Thread.currentThread().isVirtual();
1047 
1048         synchronized (timedWaitLock()) {
1049             if (seqNo != timedWaitSeqNo) {
1050                 // this timeout task is for a past timed-wait
1051                 return;









1052             }
1053             if (compareAndSetState(TIMED_WAIT, UNBLOCKED)) {
1054                 lazySubmitRunContinuation();

1055             }


1056         }
1057     }
1058 
1059     /**
1060      * Attempts to yield the current virtual thread (Thread.yield).
1061      */
1062     void tryYield() {
1063         assert Thread.currentThread() == this;
1064         setState(YIELDING);
1065         boolean yielded = false;
1066         try {
1067             yielded = yieldContinuation();  // may throw
1068         } finally {
1069             assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
1070             if (!yielded) {
1071                 assert state() == YIELDING;
1072                 setState(RUNNING);
1073             }
1074         }
1075     }

1204     @Override
1205     boolean getAndClearInterrupt() {
1206         assert Thread.currentThread() == this;
1207         boolean oldValue = interrupted;
1208         if (oldValue) {
1209             disableSuspendAndPreempt();
1210             try {
1211                 synchronized (interruptLock) {
1212                     interrupted = false;
1213                     carrierThread.clearInterrupt();
1214                 }
1215             } finally {
1216                 enableSuspendAndPreempt();
1217             }
1218         }
1219         return oldValue;
1220     }
1221 
1222     @Override
1223     Thread.State threadState() {
1224         switch (state()) {

1225             case NEW:
1226                 return Thread.State.NEW;
1227             case STARTED:
1228                 // return NEW if thread container not yet set
1229                 if (threadContainer() == null) {
1230                     return Thread.State.NEW;
1231                 } else {
1232                     return Thread.State.RUNNABLE;
1233                 }
1234             case UNPARKED:
1235             case UNBLOCKED:
1236             case YIELDED:
1237                 // runnable, not mounted
1238                 return Thread.State.RUNNABLE;
1239             case RUNNING:
1240                 // if mounted then return state of carrier thread
1241                 if (Thread.currentThread() != this) {
1242                     disableSuspendAndPreempt();
1243                     try {
1244                         synchronized (carrierThreadAccessLock()) {

1272             case BLOCKED:
1273                 return Thread.State.BLOCKED;
1274             case TERMINATED:
1275                 return Thread.State.TERMINATED;
1276             default:
1277                 throw new InternalError();
1278         }
1279     }
1280 
1281     @Override
1282     boolean alive() {
1283         int s = state;
1284         return (s != NEW && s != TERMINATED);
1285     }
1286 
1287     @Override
1288     boolean isTerminated() {
1289         return (state == TERMINATED);
1290     }
1291 















































































1292     @Override
1293     public String toString() {
1294         StringBuilder sb = new StringBuilder("VirtualThread[#");
1295         sb.append(threadId());
1296         String name = getName();
1297         if (!name.isEmpty()) {
1298             sb.append(",");
1299             sb.append(name);
1300         }
1301         sb.append("]/");
1302 
1303         // add the carrier state and thread name when mounted
1304         boolean mounted;
1305         if (Thread.currentThread() == this) {
1306             mounted = appendCarrierInfo(sb);
1307         } else {
1308             disableSuspendAndPreempt();
1309             try {
1310                 synchronized (carrierThreadAccessLock()) {
1311                     mounted = appendCarrierInfo(sb);

1457     @JvmtiMountTransition
1458     private native void startFinalTransition();
1459 
1460     @IntrinsicCandidate
1461     @JvmtiMountTransition
1462     private native void startTransition(boolean is_mount);
1463 
1464     @IntrinsicCandidate
1465     @JvmtiMountTransition
1466     private native void endTransition(boolean is_mount);
1467 
1468     @IntrinsicCandidate
1469     private static native void notifyJvmtiDisableSuspend(boolean enter);
1470 
1471     private static native void registerNatives();
1472     static {
1473         registerNatives();
1474 
1475         // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1476         var group = Thread.virtualThreadGroup();
1477 
1478         // ensure event class is initialized
1479         try {
1480             MethodHandles.lookup().ensureInitialized(VirtualThreadParkEvent.class);
1481         } catch (IllegalAccessException e) {
1482             throw new ExceptionInInitializerError(e);
1483         }
1484     }
1485 
1486     /**
1487      * Loads a VirtualThreadScheduler with the given class name. The class must be public
1488      * in an exported package, with public one-arg or no-arg constructor, and be visible
1489      * to the system class loader.
1490      * @param delegate the scheduler that the custom scheduler may delegate to
1491      * @param cn the class name of the custom scheduler
1492      */
1493     private static VirtualThreadScheduler loadCustomScheduler(VirtualThreadScheduler delegate, String cn) {
1494         VirtualThreadScheduler scheduler;
1495         try {
1496             Class<?> clazz = Class.forName(cn, true, ClassLoader.getSystemClassLoader());
1497             // 1-arg constructor
1498             try {
1499                 Constructor<?> ctor = clazz.getConstructor(VirtualThreadScheduler.class);
1500                 return (VirtualThreadScheduler) ctor.newInstance(delegate);
1501             } catch (NoSuchMethodException e) {
1502                 // 0-arg constructor
1503                 Constructor<?> ctor = clazz.getConstructor();
1504                 scheduler = (VirtualThreadScheduler) ctor.newInstance();
1505             }
1506         } catch (Exception ex) {
1507             throw new Error(ex);
1508         }
1509         System.err.println("WARNING: Using custom default scheduler, this is an experimental feature!");
1510         return scheduler;
1511     }
1512 
1513     /**
1514      * Creates the built-in ForkJoinPool scheduler.
1515      * @param wrapped true if wrapped by a custom default scheduler
1516      */
1517     private static BuiltinScheduler createBuiltinScheduler(boolean wrapped) {

1518         int parallelism, maxPoolSize, minRunnable;
1519         String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1520         String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1521         String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1522         if (parallelismValue != null) {
1523             parallelism = Integer.parseInt(parallelismValue);
1524         } else {
1525             parallelism = Runtime.getRuntime().availableProcessors();
1526         }
1527         if (maxPoolSizeValue != null) {
1528             maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1529             parallelism = Integer.min(parallelism, maxPoolSize);
1530         } else {
1531             maxPoolSize = Integer.max(parallelism, 256);
1532         }
1533         if (minRunnableValue != null) {
1534             minRunnable = Integer.parseInt(minRunnableValue);
1535         } else {
1536             minRunnable = Integer.max(parallelism / 2, 1);
1537         }
1538         return new BuiltinScheduler(parallelism, maxPoolSize, minRunnable, wrapped);
1539     }
1540 
1541     /**
1542      * The built-in ForkJoinPool scheduler.
1543      */
1544     private static class BuiltinScheduler
1545             extends ForkJoinPool implements VirtualThreadScheduler {
1546 
1547         BuiltinScheduler(int parallelism, int maxPoolSize, int minRunnable, boolean wrapped) {
1548             ForkJoinWorkerThreadFactory factory = wrapped
1549                     ? ForkJoinPool.defaultForkJoinWorkerThreadFactory
1550                     : CarrierThread::new;
1551             Thread.UncaughtExceptionHandler handler = (t, e) -> { };
1552             boolean asyncMode = true; // FIFO
1553             super(parallelism, factory, handler, asyncMode,
1554                     0, maxPoolSize, minRunnable, pool -> true, 30, SECONDS);
1555         }
1556 
1557         private void adaptAndExecute(Runnable task) {
1558             execute(ForkJoinTask.adapt(task));
1559         }
1560 
1561         @Override
1562         public void onStart(VirtualThreadTask task) {
1563             adaptAndExecute(task);
1564         }
1565 
1566         @Override
1567         public void onContinue(VirtualThreadTask task) {
1568             adaptAndExecute(task);
1569         }
1570 
1571         /**
1572          * Wraps the scheduler to avoid leaking a direct reference with
1573          * {@link VirtualThreadScheduler#current()}.
1574          */
1575         VirtualThreadScheduler createExternalView() {
1576             BuiltinScheduler builtin = this;
1577             return new VirtualThreadScheduler() {
1578                 private void execute(VirtualThreadTask task) {
1579                     var vthread = (VirtualThread) task.thread();
1580                     VirtualThreadScheduler scheduler = vthread.scheduler;
1581                     if (scheduler == this || scheduler == DEFAULT_SCHEDULER) {
1582                         builtin.adaptAndExecute(task);
1583                     } else {
1584                         throw new IllegalArgumentException();
1585                     }
1586                 }
1587                 @Override
1588                 public void onStart(VirtualThreadTask task) {
1589                     execute(task);
1590                 }
1591                 @Override
1592                 public void onContinue(VirtualThreadTask task) {
1593                     execute(task);
1594                 }
1595                 @Override
1596                 public String toString() {
1597                     return builtin.toString();
1598                 }
1599             };
1600         }
1601     }
1602 
1603     /**
1604      * Schedule a runnable task to run after a delay.
1605      */
1606     private Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1607         if (scheduler == BUILTIN_SCHEDULER) {
1608             return BUILTIN_SCHEDULER.schedule(command, delay, unit);
1609         } else {
1610             return DelayedTaskSchedulers.schedule(command, delay, unit);
1611         }
1612     }
1613 
1614     /**
1615      * Supports scheduling a runnable task to run after a delay. It uses a number
1616      * of ScheduledThreadPoolExecutor instances to reduce contention on the delayed
1617      * work queue used. This class is used when using a custom scheduler.
1618      */
1619     private static class DelayedTaskSchedulers {
1620         private static final ScheduledExecutorService[] INSTANCE = createDelayedTaskSchedulers();
1621 
1622         static Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1623             long tid = Thread.currentThread().threadId();
1624             int index = (int) tid & (INSTANCE.length - 1);
1625             return INSTANCE[index].schedule(command, delay, unit);
1626         }
1627 
1628         private static ScheduledExecutorService[] createDelayedTaskSchedulers() {
< prev index next >