1 /*
2 * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package java.lang;
26
27 import java.lang.invoke.MethodHandles;
28 import java.lang.invoke.VarHandle;
29 import java.lang.reflect.Constructor;
30 import java.util.Locale;
31 import java.util.Objects;
32 import java.util.concurrent.Executors;
33 import java.util.concurrent.ForkJoinPool;
34 import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;
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.ScheduledFuture;
40 import java.util.concurrent.ScheduledThreadPoolExecutor;
41 import java.util.concurrent.TimeUnit;
42 import jdk.internal.event.VirtualThreadEndEvent;
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 VirtualThreadScheduler BUILTIN_SCHEDULER;
71 private static final VirtualThreadScheduler DEFAULT_SCHEDULER;
72 private static final VirtualThreadScheduler EXTERNAL_VIEW;
73 private static final boolean USE_STPE;
74 static {
75 // experimental
76 String propValue = System.getProperty("jdk.virtualThreadScheduler.implClass");
77 if (propValue != null) {
78 VirtualThreadScheduler builtinScheduler = createBuiltinScheduler(true);
79 VirtualThreadScheduler externalView = createExternalView(builtinScheduler);
80 VirtualThreadScheduler defaultScheduler = loadCustomScheduler(externalView, propValue);
81 BUILTIN_SCHEDULER = builtinScheduler;
82 DEFAULT_SCHEDULER = defaultScheduler;
83 EXTERNAL_VIEW = externalView;
84 } else {
85 var builtinScheduler = createBuiltinScheduler(false);
86 BUILTIN_SCHEDULER = builtinScheduler;
87 DEFAULT_SCHEDULER = builtinScheduler;
88 EXTERNAL_VIEW = createExternalView(builtinScheduler);
89 }
90 USE_STPE = Boolean.getBoolean("jdk.virtualThreadScheduler.useSTPE");
91 }
92
93 private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
94 private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
95 private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
96 private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList");
97
98 // scheduler and continuation
99 private final VirtualThreadScheduler scheduler;
100 private final Continuation cont;
101 private final VThreadTask runContinuation;
102
103 // virtual thread state, accessed by VM
104 private volatile int state;
105
106 /*
107 * Virtual thread state transitions:
108 *
109 * NEW -> STARTED // Thread.start, schedule to run
110 * STARTED -> TERMINATED // failed to start
111 * STARTED -> RUNNING // first run
112 * RUNNING -> TERMINATED // done
113 *
114 * RUNNING -> PARKING // Thread parking with LockSupport.park
115 * PARKING -> PARKED // cont.yield successful, parked indefinitely
116 * PARKED -> UNPARKED // unparked, may be scheduled to continue
117 * UNPARKED -> RUNNING // continue execution after park
118 *
119 * PARKING -> RUNNING // cont.yield failed, need to park on carrier
120 * RUNNING -> PINNED // park on carrier
121 * PINNED -> RUNNING // unparked, continue execution on same carrier
122 *
123 * RUNNING -> TIMED_PARKING // Thread parking with LockSupport.parkNanos
124 * TIMED_PARKING -> TIMED_PARKED // cont.yield successful, timed-parked
125 * TIMED_PARKED -> UNPARKED // unparked, may be scheduled to continue
126 *
127 * TIMED_PARKING -> RUNNING // cont.yield failed, need to park on carrier
128 * RUNNING -> TIMED_PINNED // park on carrier
129 * TIMED_PINNED -> RUNNING // unparked, continue execution on same carrier
130 *
131 * RUNNING -> BLOCKING // blocking on monitor enter
132 * BLOCKING -> BLOCKED // blocked on monitor enter
133 * BLOCKED -> UNBLOCKED // unblocked, may be scheduled to continue
134 * UNBLOCKED -> RUNNING // continue execution after blocked on monitor enter
135 *
136 * RUNNING -> WAITING // transitional state during wait on monitor
137 * WAITING -> WAIT // waiting on monitor
138 * WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner
139 * WAIT -> UNBLOCKED // interrupted
140 *
141 * RUNNING -> TIMED_WAITING // transition state during timed-waiting on monitor
142 * TIMED_WAITING -> TIMED_WAIT // timed-waiting on monitor
143 * TIMED_WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner
144 * TIMED_WAIT -> UNBLOCKED // timed-out/interrupted
145 *
146 * RUNNING -> YIELDING // Thread.yield
147 * YIELDING -> YIELDED // cont.yield successful, may be scheduled to continue
148 * YIELDING -> RUNNING // cont.yield failed
149 * YIELDED -> RUNNING // continue execution after Thread.yield
150 */
151 private static final int NEW = 0;
152 private static final int STARTED = 1;
153 private static final int RUNNING = 2; // runnable-mounted
154
155 // untimed and timed parking
156 private static final int PARKING = 3;
157 private static final int PARKED = 4; // unmounted
158 private static final int PINNED = 5; // mounted
159 private static final int TIMED_PARKING = 6;
160 private static final int TIMED_PARKED = 7; // unmounted
161 private static final int TIMED_PINNED = 8; // mounted
162 private static final int UNPARKED = 9; // unmounted but runnable
163
164 // Thread.yield
165 private static final int YIELDING = 10;
166 private static final int YIELDED = 11; // unmounted but runnable
167
168 // monitor enter
169 private static final int BLOCKING = 12;
170 private static final int BLOCKED = 13; // unmounted
171 private static final int UNBLOCKED = 14; // unmounted but runnable
172
173 // monitor wait/timed-wait
174 private static final int WAITING = 15;
175 private static final int WAIT = 16; // waiting in Object.wait
176 private static final int TIMED_WAITING = 17;
177 private static final int TIMED_WAIT = 18; // waiting in timed-Object.wait
178
179 private static final int TERMINATED = 99; // final state
180
181 // parking permit made available by LockSupport.unpark
182 private volatile boolean parkPermit;
183
184 // blocking permit made available by unblocker thread when another thread exits monitor
185 private volatile boolean blockPermit;
186
187 // true when on the list of virtual threads waiting to be unblocked
188 private volatile boolean onWaitingList;
189
190 // next virtual thread on the list of virtual threads waiting to be unblocked
191 private volatile VirtualThread next;
192
193 // notified by Object.notify/notifyAll while waiting in Object.wait
194 private volatile boolean notified;
195
196 // true when waiting in Object.wait, false for VM internal uninterruptible Object.wait
197 private volatile boolean interruptibleWait;
198
199 // timed-wait support
200 private byte timedWaitSeqNo;
201
202 // timeout for timed-park and timed-wait, only accessed on current/carrier thread
203 private long timeout;
204
205 // timer task for timed-park and timed-wait, only accessed on current/carrier thread
206 private Future<?> timeoutTask;
207
208 // carrier thread when mounted, accessed by VM
209 private volatile Thread carrierThread;
210
211 // true to notifyAll after this virtual thread terminates
212 private volatile boolean notifyAllAfterTerminate;
213
214 /**
215 * Return the built-in scheduler.
216 * @param trusted true if caller is trusted, false if not trusted
217 */
218 static VirtualThreadScheduler builtinScheduler(boolean trusted) {
219 return trusted ? BUILTIN_SCHEDULER : EXTERNAL_VIEW;
220 }
221
222 /**
223 * Returns the default scheduler, usually the same as the built-in scheduler.
224 */
225 static VirtualThreadScheduler defaultScheduler() {
226 return DEFAULT_SCHEDULER;
227 }
228
229 /**
230 * Returns the continuation scope used for virtual threads.
231 */
232 static ContinuationScope continuationScope() {
233 return VTHREAD_SCOPE;
234 }
235
236 /**
237 * Returns the task to start/continue this virtual thread.
238 */
239 VirtualThreadTask virtualThreadTask() {
240 return runContinuation;
241 }
242
243 /**
244 * Creates a new {@code VirtualThread} to run the given task with the given scheduler.
245 *
246 * @param scheduler the scheduler or null for default scheduler
247 * @param preferredCarrier the preferred carrier or null
248 * @param name thread name
249 * @param characteristics characteristics
250 * @param task the task to execute
251 */
252 VirtualThread(VirtualThreadScheduler scheduler,
253 Thread preferredCarrier,
254 String name,
255 int characteristics,
256 Runnable task) {
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 VThreadTask(this);
271 } else {
272 this.runContinuation = new CustomVThreadTask(this, preferredCarrier);
273 }
274 }
275
276 /**
277 * The task to start/continue a virtual thread.
278 */
279 static non-sealed class VThreadTask implements VirtualThreadTask {
280 private final VirtualThread vthread;
281 VThreadTask(VirtualThread vthread) {
282 this.vthread = vthread;
283 }
284 @Override
285 public final Thread thread() {
286 return vthread;
287 }
288 @Override
289 public final 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 start/continue a virtual thread when using a custom scheduler.
308 */
309 static final class CustomVThreadTask extends VThreadTask {
310 private static final VarHandle ATT =
311 MhUtil.findVarHandle(MethodHandles.lookup(), "att", Object.class);
312 private final Thread preferredCarrier;
313 private volatile Object att;
314 CustomVThreadTask(VirtualThread vthread, Thread preferredCarrier) {
315 super(vthread);
316 this.preferredCarrier = preferredCarrier;
317 }
318 @Override
319 public Thread preferredCarrier() {
320 return preferredCarrier;
321 }
322 @Override
323 public Object attach(Object att) {
324 return ATT.getAndSet(this, att);
325 }
326 @Override
327 public Object attachment() {
328 return att;
329 }
330 }
331
332 /**
333 * The continuation that a virtual thread executes.
334 */
335 private static class VThreadContinuation extends Continuation {
336 VThreadContinuation(VirtualThread vthread, Runnable task) {
337 super(VTHREAD_SCOPE, wrap(vthread, task));
338 }
339 @Override
340 protected void onPinned(Continuation.Pinned reason) {
341 }
342 private static Runnable wrap(VirtualThread vthread, Runnable task) {
343 return new Runnable() {
344 @Hidden
345 @JvmtiHideEvents
346 public void run() {
347 vthread.endFirstTransition();
348 try {
349 vthread.run(task);
350 } finally {
351 vthread.startFinalTransition();
352 }
353 }
354 };
355 }
356 }
357
358 /**
359 * Runs or continues execution on the current thread. The virtual thread is mounted
360 * on the current thread before the task runs or continues. It unmounts when the
361 * task completes or yields.
362 */
363 @ChangesCurrentThread // allow mount/unmount to be inlined
364 private void runContinuation() {
365 // the carrier must be a platform thread
366 if (Thread.currentThread().isVirtual()) {
367 throw new WrongThreadException();
368 }
369
370 // set state to RUNNING
371 int initialState = state();
372 if (initialState == STARTED || initialState == UNPARKED
373 || initialState == UNBLOCKED || initialState == YIELDED) {
374 // newly started or continue after parking/blocking/Thread.yield
375 if (!compareAndSetState(initialState, RUNNING)) {
376 return;
377 }
378 // consume permit when continuing after parking or blocking. If continue
379 // after a timed-park or timed-wait then the timeout task is cancelled.
380 if (initialState == UNPARKED) {
381 cancelTimeoutTask();
382 setParkPermit(false);
383 } else if (initialState == UNBLOCKED) {
384 cancelTimeoutTask();
385 blockPermit = false;
386 }
387 } else {
388 // not runnable
389 return;
390 }
391
392 mount();
393 try {
394 cont.run();
395 } finally {
396 unmount();
397 if (cont.isDone()) {
398 afterDone();
399 } else {
400 afterYield();
401 }
402 }
403 }
404
405 /**
406 * Cancel timeout task when continuing after timed-park or timed-wait.
407 * The timeout task may be executing, or may have already completed.
408 */
409 private void cancelTimeoutTask() {
410 if (timeoutTask != null) {
411 timeoutTask.cancel(false);
412 timeoutTask = null;
413 }
414 }
415
416 /**
417 * Submits the runContinuation task to the scheduler. For the built-in scheduler,
418 * the task will be pushed to the local queue if possible, otherwise it will be
419 * pushed to an external submission queue.
420 * @param retryOnOOME true to retry indefinitely if OutOfMemoryError is thrown
421 * @throws RejectedExecutionException
422 */
423 private void submitRunContinuation(boolean retryOnOOME) {
424 boolean done = false;
425 while (!done) {
426 try {
427 // Pin the continuation to prevent the virtual thread from unmounting
428 // when submitting a task. For the default scheduler this ensures that
429 // the carrier doesn't change when pushing a task. For other schedulers
430 // it avoids deadlock that could arise due to carriers and virtual
431 // threads contending for a lock.
432 if (currentThread().isVirtual()) {
433 Continuation.pin();
434 try {
435 scheduler.onContinue(runContinuation);
436 } finally {
437 Continuation.unpin();
438 }
439 } else {
440 scheduler.onContinue(runContinuation);
441 }
442 done = true;
443 } catch (RejectedExecutionException ree) {
444 submitFailed(ree);
445 throw ree;
446 } catch (OutOfMemoryError e) {
447 if (retryOnOOME) {
448 U.park(false, 100_000_000); // 100ms
449 } else {
450 throw e;
451 }
452 }
453 }
454 }
455
456 /**
457 * Submits the runContinuation task to the scheduler. For the default scheduler,
458 * and calling it on a worker thread, the task will be pushed to the local queue,
459 * otherwise it will be pushed to an external submission queue.
460 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
461 * @throws RejectedExecutionException
462 */
463 private void submitRunContinuation() {
464 submitRunContinuation(true);
465 }
466
467 /**
468 * Invoked from a carrier thread to lazy submit the runContinuation task to the
469 * carrier's local queue if the queue is empty. If not empty, or invoked by a thread
470 * for a custom scheduler, then it just submits the task to the scheduler.
471 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
472 * @throws RejectedExecutionException
473 * @see ForkJoinPool#lazySubmit(ForkJoinTask)
474 */
475 private void lazySubmitRunContinuation() {
476 assert !currentThread().isVirtual();
477 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
478 try {
479 ct.getPool().lazySubmit(ForkJoinTask.adapt(runContinuation));
480 } catch (RejectedExecutionException ree) {
481 submitFailed(ree);
482 throw ree;
483 } catch (OutOfMemoryError e) {
484 submitRunContinuation();
485 }
486 } else {
487 submitRunContinuation();
488 }
489 }
490
491 /**
492 * Invoked from a carrier thread to externally submit the runContinuation task to the
493 * scheduler. If invoked by a thread for a custom scheduler, then it just submits the
494 * task to the scheduler.
495 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
496 * @throws RejectedExecutionException
497 * @see ForkJoinPool#externalSubmit(ForkJoinTask)
498 */
499 private void externalSubmitRunContinuation() {
500 assert !currentThread().isVirtual();
501 if (currentThread() instanceof CarrierThread ct) {
502 try {
503 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
504 } catch (RejectedExecutionException ree) {
505 submitFailed(ree);
506 throw ree;
507 } catch (OutOfMemoryError e) {
508 submitRunContinuation();
509 }
510 } else {
511 submitRunContinuation();
512 }
513 }
514
515 /**
516 * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
517 */
518 private void submitFailed(RejectedExecutionException ree) {
519 var event = new VirtualThreadSubmitFailedEvent();
520 if (event.isEnabled()) {
521 event.javaThreadId = threadId();
522 event.exceptionMessage = ree.getMessage();
523 event.commit();
524 }
525 }
526
527 /**
528 * Runs a task in the context of this virtual thread.
529 */
530 private void run(Runnable task) {
531 assert Thread.currentThread() == this && state == RUNNING;
532
533 // emit JFR event if enabled
534 if (VirtualThreadStartEvent.isTurnedOn()) {
535 var event = new VirtualThreadStartEvent();
536 event.javaThreadId = threadId();
537 event.commit();
538 }
539
540 Object bindings = Thread.scopedValueBindings();
541 try {
542 runWith(bindings, task);
543 } catch (Throwable exc) {
544 dispatchUncaughtException(exc);
545 } finally {
546 // pop any remaining scopes from the stack, this may block
547 StackableScope.popAll();
548
549 // emit JFR event if enabled
550 if (VirtualThreadEndEvent.isTurnedOn()) {
551 var event = new VirtualThreadEndEvent();
552 event.javaThreadId = threadId();
553 event.commit();
554 }
555 }
556 }
557
558 /**
559 * Mounts this virtual thread onto the current platform thread. On
560 * return, the current thread is the virtual thread.
561 */
562 @ChangesCurrentThread
563 @ReservedStackAccess
564 private void mount() {
565 startTransition(/*mount*/true);
566 // We assume following volatile accesses provide equivalent
567 // of acquire ordering, otherwise we need U.loadFence() here.
568
569 // sets the carrier thread
570 Thread carrier = Thread.currentCarrierThread();
571 setCarrierThread(carrier);
572
573 // sync up carrier thread interrupted status if needed
574 if (interrupted) {
575 carrier.setInterrupt();
576 } else if (carrier.isInterrupted()) {
577 synchronized (interruptLock) {
578 // need to recheck interrupted status
579 if (!interrupted) {
580 carrier.clearInterrupt();
581 }
582 }
583 }
584
585 // set Thread.currentThread() to return this virtual thread
586 carrier.setCurrentThread(this);
587 }
588
589 /**
590 * Unmounts this virtual thread from the carrier. On return, the
591 * current thread is the current platform thread.
592 */
593 @ChangesCurrentThread
594 @ReservedStackAccess
595 private void unmount() {
596 assert !Thread.holdsLock(interruptLock);
597
598 // set Thread.currentThread() to return the platform thread
599 Thread carrier = this.carrierThread;
600 carrier.setCurrentThread(carrier);
601
602 // break connection to carrier thread, synchronized with interrupt
603 synchronized (interruptLock) {
604 setCarrierThread(null);
605 }
606 carrier.clearInterrupt();
607
608 // We assume previous volatile accesses provide equivalent
609 // of release ordering, otherwise we need U.storeFence() here.
610 endTransition(/*mount*/false);
611 }
612
613 /**
614 * Invokes Continuation.yield, notifying JVMTI (if enabled) to hide frames until
615 * the continuation continues.
616 */
617 @Hidden
618 private boolean yieldContinuation() {
619 startTransition(/*mount*/false);
620 try {
621 return Continuation.yield(VTHREAD_SCOPE);
622 } finally {
623 endTransition(/*mount*/true);
624 }
625 }
626
627 /**
628 * Invoked in the context of the carrier thread after the Continuation yields when
629 * parking, blocking on monitor enter, Object.wait, or Thread.yield.
630 */
631 private void afterYield() {
632 assert carrierThread == null;
633
634 // re-adjust parallelism if the virtual thread yielded when compensating
635 if (currentThread() instanceof CarrierThread ct) {
636 ct.endBlocking();
637 }
638
639 int s = state();
640
641 // LockSupport.park/parkNanos
642 if (s == PARKING || s == TIMED_PARKING) {
643 int newState;
644 if (s == PARKING) {
645 setState(newState = PARKED);
646 } else {
647 // schedule unpark
648 long timeout = this.timeout;
649 assert timeout > 0;
650 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS);
651 setState(newState = TIMED_PARKED);
652 }
653
654 // may have been unparked while parking
655 if (parkPermit && compareAndSetState(newState, UNPARKED)) {
656 // lazy submit if local queue is empty
657 lazySubmitRunContinuation();
658 }
659 return;
660 }
661
662 // Thread.yield
663 if (s == YIELDING) {
664 setState(YIELDED);
665
666 // external submit if there are no tasks in the local task queue
667 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
668 externalSubmitRunContinuation();
669 } else {
670 submitRunContinuation();
671 }
672 return;
673 }
674
675 // blocking on monitorenter
676 if (s == BLOCKING) {
677 setState(BLOCKED);
678
679 // may have been unblocked while blocking
680 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
681 // lazy submit if local queue is empty
682 lazySubmitRunContinuation();
683 }
684 return;
685 }
686
687 // Object.wait
688 if (s == WAITING || s == TIMED_WAITING) {
689 int newState;
690 boolean blocked;
691 boolean interruptible = interruptibleWait;
692 if (s == WAITING) {
693 setState(newState = WAIT);
694 // may have been notified while in transition
695 blocked = notified && compareAndSetState(WAIT, BLOCKED);
696 } else {
697 // For timed-wait, a timeout task is scheduled to execute. The timeout
698 // task will change the thread state to UNBLOCKED and submit the thread
699 // to the scheduler. A sequence number is used to ensure that the timeout
700 // task only unblocks the thread for this timed-wait. We synchronize with
701 // the timeout task to coordinate access to the sequence number and to
702 // ensure the timeout task doesn't execute until the thread has got to
703 // the TIMED_WAIT state.
704 long timeout = this.timeout;
705 assert timeout > 0;
706 synchronized (timedWaitLock()) {
707 byte seqNo = ++timedWaitSeqNo;
708 timeoutTask = schedule(() -> waitTimeoutExpired(seqNo), timeout, MILLISECONDS);
709 setState(newState = TIMED_WAIT);
710 // May have been notified while in transition. This must be done while
711 // holding the monitor to avoid changing the state of a new timed wait call.
712 blocked = notified && compareAndSetState(TIMED_WAIT, BLOCKED);
713 }
714 }
715
716 if (blocked) {
717 // may have been unblocked already
718 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
719 lazySubmitRunContinuation();
720 }
721 } else {
722 // may have been interrupted while in transition to wait state
723 if (interruptible && interrupted && compareAndSetState(newState, UNBLOCKED)) {
724 lazySubmitRunContinuation();
725 }
726 }
727 return;
728 }
729
730 assert false;
731 }
732
733 /**
734 * Invoked after the continuation completes.
735 */
736 private void afterDone() {
737 afterDone(true);
738 }
739
740 /**
741 * Invoked after the continuation completes (or start failed). Sets the thread
742 * state to TERMINATED and notifies anyone waiting for the thread to terminate.
743 *
744 * @param notifyContainer true if its container should be notified
745 */
746 private void afterDone(boolean notifyContainer) {
747 assert carrierThread == null;
748 setState(TERMINATED);
749
750 // notifyAll to wakeup any threads waiting for this thread to terminate
751 if (notifyAllAfterTerminate) {
752 synchronized (this) {
753 notifyAll();
754 }
755 }
756
757 // notify container
758 if (notifyContainer) {
759 threadContainer().remove(this);
760 }
761
762 // clear references to thread locals
763 clearReferences();
764 }
765
766 /**
767 * Schedules this {@code VirtualThread} to execute.
768 *
769 * @throws IllegalStateException if the container is shutdown or closed
770 * @throws IllegalThreadStateException if the thread has already been started
771 * @throws RejectedExecutionException if the scheduler cannot accept a task
772 */
773 @Override
774 void start(ThreadContainer container) {
775 if (!compareAndSetState(NEW, STARTED)) {
776 throw new IllegalThreadStateException("Already started");
777 }
778
779 // bind thread to container
780 assert threadContainer() == null;
781 setThreadContainer(container);
782
783 // start thread
784 boolean addedToContainer = false;
785 boolean started = false;
786 try {
787 container.add(this); // may throw
788 addedToContainer = true;
789
790 // scoped values may be inherited
791 inheritScopedValueBindings(container);
792
793 // submit task to schedule
794 try {
795 if (currentThread().isVirtual()) {
796 Continuation.pin();
797 try {
798 if (scheduler == BUILTIN_SCHEDULER
799 && currentCarrierThread() instanceof CarrierThread ct) {
800 ForkJoinPool pool = ct.getPool();
801 ForkJoinTask<?> task = ForkJoinTask.adapt(runContinuation);
802 pool.externalSubmit(task);
803 } else {
804 scheduler.onStart(runContinuation);
805 }
806 } finally {
807 Continuation.unpin();
808 }
809 } else {
810 scheduler.onStart(runContinuation);
811 }
812 } catch (RejectedExecutionException ree) {
813 submitFailed(ree);
814 throw ree;
815 }
816
817 started = true;
818 } finally {
819 if (!started) {
820 afterDone(addedToContainer);
821 }
822 }
823 }
824
825 @Override
826 public void start() {
827 start(ThreadContainers.root());
828 }
829
830 @Override
831 public void run() {
832 // do nothing
833 }
834
835 /**
836 * Invoked by Thread.join before a thread waits for this virtual thread to terminate.
837 */
838 void beforeJoin() {
839 notifyAllAfterTerminate = true;
840 }
841
842 /**
843 * Parks until unparked or interrupted. If already unparked then the parking
844 * permit is consumed and this method completes immediately (meaning it doesn't
845 * yield). It also completes immediately if the interrupted status is set.
846 */
847 @Override
848 void park() {
849 assert Thread.currentThread() == this;
850
851 // complete immediately if parking permit available or interrupted
852 if (getAndSetParkPermit(false) || interrupted)
853 return;
854
855 // park the thread
856 boolean yielded = false;
857 setState(PARKING);
858 try {
859 yielded = yieldContinuation();
860 } catch (OutOfMemoryError e) {
861 // park on carrier
862 } finally {
863 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
864 if (!yielded) {
865 assert state() == PARKING;
866 setState(RUNNING);
867 }
868 }
869
870 // park on the carrier thread when pinned
871 if (!yielded) {
872 parkOnCarrierThread(false, 0);
873 }
874 }
875
876 /**
877 * Parks up to the given waiting time or until unparked or interrupted.
878 * If already unparked then the parking permit is consumed and this method
879 * completes immediately (meaning it doesn't yield). It also completes immediately
880 * if the interrupted status is set or the waiting time is {@code <= 0}.
881 *
882 * @param nanos the maximum number of nanoseconds to wait.
883 */
884 @Override
885 void parkNanos(long nanos) {
886 assert Thread.currentThread() == this;
887
888 // complete immediately if parking permit available or interrupted
889 if (getAndSetParkPermit(false) || interrupted)
890 return;
891
892 // park the thread for the waiting time
893 if (nanos > 0) {
894 long startTime = System.nanoTime();
895
896 // park the thread, afterYield will schedule the thread to unpark
897 boolean yielded = false;
898 timeout = nanos;
899 setState(TIMED_PARKING);
900 try {
901 yielded = yieldContinuation();
902 } catch (OutOfMemoryError e) {
903 // park on carrier
904 } finally {
905 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
906 if (!yielded) {
907 assert state() == TIMED_PARKING;
908 setState(RUNNING);
909 }
910 }
911
912 // park on carrier thread for remaining time when pinned (or OOME)
913 if (!yielded) {
914 long remainingNanos = nanos - (System.nanoTime() - startTime);
915 parkOnCarrierThread(true, remainingNanos);
916 }
917 }
918 }
919
920 /**
921 * Parks the current carrier thread up to the given waiting time or until
922 * unparked or interrupted. If the virtual thread is interrupted then the
923 * interrupted status will be propagated to the carrier thread.
924 * @param timed true for a timed park, false for untimed
925 * @param nanos the waiting time in nanoseconds
926 */
927 private void parkOnCarrierThread(boolean timed, long nanos) {
928 assert state() == RUNNING;
929
930 setState(timed ? TIMED_PINNED : PINNED);
931 try {
932 if (!parkPermit) {
933 if (!timed) {
934 U.park(false, 0);
935 } else if (nanos > 0) {
936 U.park(false, nanos);
937 }
938 }
939 } finally {
940 setState(RUNNING);
941 }
942
943 // consume parking permit
944 setParkPermit(false);
945
946 // JFR jdk.VirtualThreadPinned event
947 postPinnedEvent("LockSupport.park");
948 }
949
950 /**
951 * Call into VM when pinned to record a JFR jdk.VirtualThreadPinned event.
952 * Recording the event in the VM avoids having JFR event recorded in Java
953 * with the same name, but different ID, to events recorded by the VM.
954 */
955 @Hidden
956 private static native void postPinnedEvent(String op);
957
958 /**
959 * Re-enables this virtual thread for scheduling. If this virtual thread is parked
960 * then its task is scheduled to continue, otherwise its next call to {@code park} or
961 * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block.
962 * @param lazySubmit to use lazySubmit if possible
963 * @throws RejectedExecutionException if the scheduler cannot accept a task
964 */
965 private void unpark(boolean lazySubmit) {
966 if (!getAndSetParkPermit(true) && currentThread() != this) {
967 int s = state();
968
969 // unparked while parked
970 if ((s == PARKED || s == TIMED_PARKED) && compareAndSetState(s, UNPARKED)) {
971
972 if (lazySubmit && currentThread().isVirtual()) {
973 Continuation.pin();
974 try {
975 if (scheduler == BUILTIN_SCHEDULER
976 && currentCarrierThread() instanceof CarrierThread ct) {
977 ct.getPool().lazySubmit(ForkJoinTask.adapt(runContinuation));
978 return;
979 }
980 } catch (RejectedExecutionException ree) {
981 submitFailed(ree);
982 throw ree;
983 } catch (OutOfMemoryError e) {
984 // fall-though
985 } finally {
986 Continuation.unpin();
987 }
988 }
989
990 submitRunContinuation();
991 return;
992 }
993
994 // unparked while parked when pinned
995 if (s == PINNED || s == TIMED_PINNED) {
996 // unpark carrier thread when pinned
997 disableSuspendAndPreempt();
998 try {
999 synchronized (carrierThreadAccessLock()) {
1000 Thread carrier = carrierThread;
1001 if (carrier != null && ((s = state()) == PINNED || s == TIMED_PINNED)) {
1002 U.unpark(carrier);
1003 }
1004 }
1005 } finally {
1006 enableSuspendAndPreempt();
1007 }
1008 return;
1009 }
1010 }
1011 }
1012
1013 @Override
1014 void unpark() {
1015 unpark(false);
1016 }
1017
1018 /**
1019 * Invoked by unblocker thread to unblock this virtual thread.
1020 */
1021 private void unblock() {
1022 assert !Thread.currentThread().isVirtual();
1023 blockPermit = true;
1024 if (state() == BLOCKED && compareAndSetState(BLOCKED, UNBLOCKED)) {
1025 submitRunContinuation();
1026 }
1027 }
1028
1029 /**
1030 * Invoked by FJP worker thread or STPE thread when park timeout expires.
1031 */
1032 private void parkTimeoutExpired() {
1033 assert !VirtualThread.currentThread().isVirtual();
1034 unpark(true);
1035 }
1036
1037 /**
1038 * Invoked by FJP worker thread or STPE thread when wait timeout expires.
1039 * If the virtual thread is in timed-wait then this method will unblock the thread
1040 * and submit its task so that it continues and attempts to reenter the monitor.
1041 * This method does nothing if the thread has been woken by notify or interrupt.
1042 */
1043 private void waitTimeoutExpired(byte seqNo) {
1044 assert !Thread.currentThread().isVirtual();
1045
1046 synchronized (timedWaitLock()) {
1047 if (seqNo != timedWaitSeqNo) {
1048 // this timeout task is for a past timed-wait
1049 return;
1050 }
1051 if (!compareAndSetState(TIMED_WAIT, UNBLOCKED)) {
1052 // already notified (or interrupted)
1053 return;
1054 }
1055 }
1056
1057 lazySubmitRunContinuation();
1058 }
1059
1060 /**
1061 * Attempts to yield the current virtual thread (Thread.yield).
1062 */
1063 void tryYield() {
1064 assert Thread.currentThread() == this;
1065 setState(YIELDING);
1066 boolean yielded = false;
1067 try {
1068 yielded = yieldContinuation(); // may throw
1069 } finally {
1070 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
1071 if (!yielded) {
1072 assert state() == YIELDING;
1073 setState(RUNNING);
1074 }
1075 }
1076 }
1077
1078 /**
1079 * Sleep the current thread for the given sleep time (in nanoseconds). If
1080 * nanos is 0 then the thread will attempt to yield.
1081 *
1082 * @implNote This implementation parks the thread for the given sleeping time
1083 * and will therefore be observed in PARKED state during the sleep. Parking
1084 * will consume the parking permit so this method makes available the parking
1085 * permit after the sleep. This may be observed as a spurious, but benign,
1086 * wakeup when the thread subsequently attempts to park.
1087 *
1088 * @param nanos the maximum number of nanoseconds to sleep
1089 * @throws InterruptedException if interrupted while sleeping
1090 */
1091 void sleepNanos(long nanos) throws InterruptedException {
1092 assert Thread.currentThread() == this && nanos >= 0;
1093 if (getAndClearInterrupt())
1094 throw new InterruptedException();
1095 if (nanos == 0) {
1096 tryYield();
1097 } else {
1098 // park for the sleep time
1099 try {
1100 long remainingNanos = nanos;
1101 long startNanos = System.nanoTime();
1102 while (remainingNanos > 0) {
1103 parkNanos(remainingNanos);
1104 if (getAndClearInterrupt()) {
1105 throw new InterruptedException();
1106 }
1107 remainingNanos = nanos - (System.nanoTime() - startNanos);
1108 }
1109 } finally {
1110 // may have been unparked while sleeping
1111 setParkPermit(true);
1112 }
1113 }
1114 }
1115
1116 @Override
1117 void blockedOn(Interruptible b) {
1118 disableSuspendAndPreempt();
1119 try {
1120 super.blockedOn(b);
1121 } finally {
1122 enableSuspendAndPreempt();
1123 }
1124 }
1125
1126 @Override
1127 public void interrupt() {
1128 if (Thread.currentThread() != this) {
1129 // if current thread is a virtual thread then prevent it from being
1130 // suspended or unmounted when entering or holding interruptLock
1131 Interruptible blocker;
1132 disableSuspendAndPreempt();
1133 try {
1134 synchronized (interruptLock) {
1135 interrupted = true;
1136 blocker = nioBlocker();
1137 if (blocker != null) {
1138 blocker.interrupt(this);
1139 }
1140
1141 // interrupt carrier thread if mounted
1142 Thread carrier = carrierThread;
1143 if (carrier != null) carrier.setInterrupt();
1144 }
1145 } finally {
1146 enableSuspendAndPreempt();
1147 }
1148
1149 // notify blocker after releasing interruptLock
1150 if (blocker != null) {
1151 blocker.postInterrupt();
1152 }
1153
1154 // make available parking permit, unpark thread if parked
1155 unpark();
1156
1157 // if thread is waiting in Object.wait then schedule to try to reenter
1158 int s = state();
1159 if ((s == WAIT || s == TIMED_WAIT) && compareAndSetState(s, UNBLOCKED)) {
1160 submitRunContinuation();
1161 }
1162
1163 } else {
1164 interrupted = true;
1165 carrierThread.setInterrupt();
1166 setParkPermit(true);
1167 }
1168 }
1169
1170 @Override
1171 public boolean isInterrupted() {
1172 return interrupted;
1173 }
1174
1175 @Override
1176 boolean getAndClearInterrupt() {
1177 assert Thread.currentThread() == this;
1178 boolean oldValue = interrupted;
1179 if (oldValue) {
1180 disableSuspendAndPreempt();
1181 try {
1182 synchronized (interruptLock) {
1183 interrupted = false;
1184 carrierThread.clearInterrupt();
1185 }
1186 } finally {
1187 enableSuspendAndPreempt();
1188 }
1189 }
1190 return oldValue;
1191 }
1192
1193 @Override
1194 Thread.State threadState() {
1195 switch (state()) {
1196 case NEW:
1197 return Thread.State.NEW;
1198 case STARTED:
1199 // return NEW if thread container not yet set
1200 if (threadContainer() == null) {
1201 return Thread.State.NEW;
1202 } else {
1203 return Thread.State.RUNNABLE;
1204 }
1205 case UNPARKED:
1206 case UNBLOCKED:
1207 case YIELDED:
1208 // runnable, not mounted
1209 return Thread.State.RUNNABLE;
1210 case RUNNING:
1211 // if mounted then return state of carrier thread
1212 if (Thread.currentThread() != this) {
1213 disableSuspendAndPreempt();
1214 try {
1215 synchronized (carrierThreadAccessLock()) {
1216 Thread carrierThread = this.carrierThread;
1217 if (carrierThread != null) {
1218 return carrierThread.threadState();
1219 }
1220 }
1221 } finally {
1222 enableSuspendAndPreempt();
1223 }
1224 }
1225 // runnable, mounted
1226 return Thread.State.RUNNABLE;
1227 case PARKING:
1228 case TIMED_PARKING:
1229 case WAITING:
1230 case TIMED_WAITING:
1231 case YIELDING:
1232 // runnable, in transition
1233 return Thread.State.RUNNABLE;
1234 case PARKED:
1235 case PINNED:
1236 case WAIT:
1237 return Thread.State.WAITING;
1238 case TIMED_PARKED:
1239 case TIMED_PINNED:
1240 case TIMED_WAIT:
1241 return Thread.State.TIMED_WAITING;
1242 case BLOCKING:
1243 case BLOCKED:
1244 return Thread.State.BLOCKED;
1245 case TERMINATED:
1246 return Thread.State.TERMINATED;
1247 default:
1248 throw new InternalError();
1249 }
1250 }
1251
1252 @Override
1253 boolean alive() {
1254 int s = state;
1255 return (s != NEW && s != TERMINATED);
1256 }
1257
1258 @Override
1259 boolean isTerminated() {
1260 return (state == TERMINATED);
1261 }
1262
1263 @Override
1264 public String toString() {
1265 StringBuilder sb = new StringBuilder("VirtualThread[#");
1266 sb.append(threadId());
1267 String name = getName();
1268 if (!name.isEmpty()) {
1269 sb.append(",");
1270 sb.append(name);
1271 }
1272 sb.append("]/");
1273
1274 // add the carrier state and thread name when mounted
1275 boolean mounted;
1276 if (Thread.currentThread() == this) {
1277 mounted = appendCarrierInfo(sb);
1278 } else {
1279 disableSuspendAndPreempt();
1280 try {
1281 synchronized (carrierThreadAccessLock()) {
1282 mounted = appendCarrierInfo(sb);
1283 }
1284 } finally {
1285 enableSuspendAndPreempt();
1286 }
1287 }
1288
1289 // add virtual thread state when not mounted
1290 if (!mounted) {
1291 String stateAsString = threadState().toString();
1292 sb.append(stateAsString.toLowerCase(Locale.ROOT));
1293 }
1294
1295 return sb.toString();
1296 }
1297
1298 /**
1299 * Appends the carrier state and thread name to the string buffer if mounted.
1300 * @return true if mounted, false if not mounted
1301 */
1302 private boolean appendCarrierInfo(StringBuilder sb) {
1303 assert Thread.currentThread() == this || Thread.holdsLock(carrierThreadAccessLock());
1304 Thread carrier = carrierThread;
1305 if (carrier != null) {
1306 String stateAsString = carrier.threadState().toString();
1307 sb.append(stateAsString.toLowerCase(Locale.ROOT));
1308 sb.append('@');
1309 sb.append(carrier.getName());
1310 return true;
1311 } else {
1312 return false;
1313 }
1314 }
1315
1316 @Override
1317 public int hashCode() {
1318 return (int) threadId();
1319 }
1320
1321 @Override
1322 public boolean equals(Object obj) {
1323 return obj == this;
1324 }
1325
1326 /**
1327 * Returns the lock object to synchronize on when accessing carrierThread.
1328 * The lock prevents carrierThread from being reset to null during unmount.
1329 */
1330 private Object carrierThreadAccessLock() {
1331 // return interruptLock as unmount has to coordinate with interrupt
1332 return interruptLock;
1333 }
1334
1335 /**
1336 * Returns a lock object for coordinating timed-wait setup and timeout handling.
1337 */
1338 private Object timedWaitLock() {
1339 // use this object for now to avoid the overhead of introducing another lock
1340 return runContinuation;
1341 }
1342
1343 /**
1344 * Disallow the current thread be suspended or preempted.
1345 */
1346 private void disableSuspendAndPreempt() {
1347 notifyJvmtiDisableSuspend(true);
1348 Continuation.pin();
1349 }
1350
1351 /**
1352 * Allow the current thread be suspended or preempted.
1353 */
1354 private void enableSuspendAndPreempt() {
1355 Continuation.unpin();
1356 notifyJvmtiDisableSuspend(false);
1357 }
1358
1359 // -- wrappers for get/set of state, parking permit, and carrier thread --
1360
1361 private int state() {
1362 return state; // volatile read
1363 }
1364
1365 private void setState(int newValue) {
1366 state = newValue; // volatile write
1367 }
1368
1369 private boolean compareAndSetState(int expectedValue, int newValue) {
1370 return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1371 }
1372
1373 private boolean compareAndSetOnWaitingList(boolean expectedValue, boolean newValue) {
1374 return U.compareAndSetBoolean(this, ON_WAITING_LIST, expectedValue, newValue);
1375 }
1376
1377 private void setParkPermit(boolean newValue) {
1378 if (parkPermit != newValue) {
1379 parkPermit = newValue;
1380 }
1381 }
1382
1383 private boolean getAndSetParkPermit(boolean newValue) {
1384 if (parkPermit != newValue) {
1385 return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1386 } else {
1387 return newValue;
1388 }
1389 }
1390
1391 private void setCarrierThread(Thread carrier) {
1392 // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1393 this.carrierThread = carrier;
1394 }
1395
1396 // The following four methods notify the VM when a "transition" starts and ends.
1397 // A "mount transition" embodies the steps to transfer control from a platform
1398 // thread to a virtual thread, changing the thread identity, and starting or
1399 // resuming the virtual thread's continuation on the carrier.
1400 // An "unmount transition" embodies the steps to transfer control from a virtual
1401 // thread to its carrier, suspending the virtual thread's continuation, and
1402 // restoring the thread identity to the platform thread.
1403 // The notifications to the VM are necessary in order to coordinate with functions
1404 // (JVMTI mostly) that disable transitions for one or all virtual threads. Starting
1405 // a transition may block if transitions are disabled. Ending a transition may
1406 // notify a thread that is waiting to disable transitions. The notifications are
1407 // also used to post JVMTI events for virtual thread start and end.
1408
1409 @IntrinsicCandidate
1410 @JvmtiMountTransition
1411 private native void endFirstTransition();
1412
1413 @IntrinsicCandidate
1414 @JvmtiMountTransition
1415 private native void startFinalTransition();
1416
1417 @IntrinsicCandidate
1418 @JvmtiMountTransition
1419 private native void startTransition(boolean mount);
1420
1421 @IntrinsicCandidate
1422 @JvmtiMountTransition
1423 private native void endTransition(boolean mount);
1424
1425 @IntrinsicCandidate
1426 private static native void notifyJvmtiDisableSuspend(boolean enter);
1427
1428 private static native void registerNatives();
1429 static {
1430 registerNatives();
1431
1432 // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1433 var group = Thread.virtualThreadGroup();
1434 }
1435
1436 /**
1437 * Loads a VirtualThreadScheduler with the given class name. The class must be public
1438 * in an exported package, with public one-arg or no-arg constructor, and be visible
1439 * to the system class loader.
1440 * @param delegate the scheduler that the custom scheduler may delegate to
1441 * @param cn the class name of the custom scheduler
1442 */
1443 private static VirtualThreadScheduler loadCustomScheduler(VirtualThreadScheduler delegate, String cn) {
1444 VirtualThreadScheduler scheduler;
1445 try {
1446 Class<?> clazz = Class.forName(cn, true, ClassLoader.getSystemClassLoader());
1447 // 1-arg constructor
1448 try {
1449 Constructor<?> ctor = clazz.getConstructor(VirtualThreadScheduler.class);
1450 return (VirtualThreadScheduler) ctor.newInstance(delegate);
1451 } catch (NoSuchMethodException e) {
1452 // 0-arg constructor
1453 Constructor<?> ctor = clazz.getConstructor();
1454 scheduler = (VirtualThreadScheduler) ctor.newInstance();
1455 }
1456 } catch (Exception ex) {
1457 throw new Error(ex);
1458 }
1459 System.err.println("WARNING: Using custom default scheduler, this is an experimental feature!");
1460 return scheduler;
1461 }
1462
1463 /**
1464 * Creates the built-in ForkJoinPool scheduler.
1465 * @param wrapped true if wrapped by a custom default scheduler
1466 */
1467 private static VirtualThreadScheduler createBuiltinScheduler(boolean wrapped) {
1468 int parallelism, maxPoolSize, minRunnable;
1469 String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1470 String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1471 String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1472 if (parallelismValue != null) {
1473 parallelism = Integer.parseInt(parallelismValue);
1474 } else {
1475 parallelism = Runtime.getRuntime().availableProcessors();
1476 }
1477 if (maxPoolSizeValue != null) {
1478 maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1479 parallelism = Integer.min(parallelism, maxPoolSize);
1480 } else {
1481 maxPoolSize = Integer.max(parallelism, 256);
1482 }
1483 if (minRunnableValue != null) {
1484 minRunnable = Integer.parseInt(minRunnableValue);
1485 } else {
1486 minRunnable = Integer.max(parallelism / 2, 1);
1487 }
1488 ForkJoinWorkerThreadFactory factory;
1489 if (wrapped) {
1490 factory = ForkJoinPool.defaultForkJoinWorkerThreadFactory;
1491 } else {
1492 String cn = System.getProperty("jdk.virtualThreadScheduler.threadFactory");
1493 if (cn != null) {
1494 try {
1495 Class<?> clazz = Class.forName(cn, true, ClassLoader.getSystemClassLoader());
1496 Constructor<?> ctor = clazz.getConstructor();
1497 factory = (ForkJoinWorkerThreadFactory) ctor.newInstance();
1498 } catch (Exception ex) {
1499 throw new Error(ex);
1500 }
1501 } else {
1502 factory = CarrierThread::new;
1503 }
1504 }
1505 return new BuiltinForkJoinPoolScheduler(parallelism, maxPoolSize, minRunnable, factory);
1506 }
1507
1508 /**
1509 * The built-in ForkJoinPool scheduler.
1510 */
1511 private static class BuiltinForkJoinPoolScheduler
1512 extends ForkJoinPool implements VirtualThreadScheduler {
1513
1514 BuiltinForkJoinPoolScheduler(int parallelism,
1515 int maxPoolSize,
1516 int minRunnable,
1517 ForkJoinWorkerThreadFactory factory) {
1518 Thread.UncaughtExceptionHandler handler = (t, e) -> { };
1519 boolean asyncMode = true; // FIFO
1520 super(parallelism, factory, handler, asyncMode,
1521 0, maxPoolSize, minRunnable, pool -> true, 30L, SECONDS);
1522 }
1523
1524 @Override
1525 public void onStart(VirtualThreadTask task) {
1526 execute(ForkJoinTask.adapt(task));
1527 }
1528
1529 @Override
1530 public void onContinue(VirtualThreadTask task) {
1531 execute(ForkJoinTask.adapt(task));
1532 }
1533
1534 @Override
1535 public ScheduledFuture<?> schedule(Runnable task, long delay, TimeUnit unit) {
1536 return super.schedule(task, delay, unit);
1537 }
1538 }
1539
1540 /**
1541 * Wraps the scheduler to avoid leaking a direct reference to built-in scheduler.
1542 */
1543 static VirtualThreadScheduler createExternalView(VirtualThreadScheduler delegate) {
1544 return new VirtualThreadScheduler() {
1545 private void check(VirtualThreadTask task) {
1546 var vthread = (VirtualThread) task.thread();
1547 VirtualThreadScheduler scheduler = vthread.scheduler;
1548 if (scheduler != this && scheduler != DEFAULT_SCHEDULER) {
1549 throw new IllegalArgumentException();
1550 }
1551 }
1552 @Override
1553 public void onStart(VirtualThreadTask task) {
1554 check(task);
1555 delegate.onStart(task);
1556 }
1557 @Override
1558 public void onContinue(VirtualThreadTask task) {
1559 check(task);
1560 delegate.onContinue(task);
1561 }
1562 @Override
1563 public String toString() {
1564 return delegate.toString();
1565 }
1566 };
1567 }
1568
1569 /**
1570 * Schedule a runnable task to run after a delay.
1571 */
1572 private Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1573 if (USE_STPE) {
1574 return DelayedTaskSchedulers.schedule(command, delay, unit);
1575 } else {
1576 return scheduler.schedule(command, delay, unit);
1577 }
1578 }
1579
1580 /**
1581 * Supports scheduling a runnable task to run after a delay. It uses a number
1582 * of ScheduledThreadPoolExecutor instances to reduce contention on the delayed
1583 * work queue used. This class is used when using a custom scheduler.
1584 */
1585 static class DelayedTaskSchedulers {
1586 private static final ScheduledExecutorService[] INSTANCE = createDelayedTaskSchedulers();
1587
1588 static Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1589 long tid = Thread.currentThread().threadId();
1590 int index = (int) tid & (INSTANCE.length - 1);
1591 return INSTANCE[index].schedule(command, delay, unit);
1592 }
1593
1594 private static ScheduledExecutorService[] createDelayedTaskSchedulers() {
1595 String propName = "jdk.virtualThreadScheduler.timerQueues";
1596 String propValue = System.getProperty(propName);
1597 int queueCount;
1598 if (propValue != null) {
1599 queueCount = Integer.parseInt(propValue);
1600 if (queueCount != Integer.highestOneBit(queueCount)) {
1601 throw new RuntimeException("Value of " + propName + " must be power of 2");
1602 }
1603 } else {
1604 int ncpus = Runtime.getRuntime().availableProcessors();
1605 queueCount = Math.max(Integer.highestOneBit(ncpus / 4), 1);
1606 }
1607 var schedulers = new ScheduledExecutorService[queueCount];
1608 for (int i = 0; i < queueCount; i++) {
1609 ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor)
1610 Executors.newScheduledThreadPool(1, task -> {
1611 Thread t = InnocuousThread.newThread("VirtualThread-unparker", task);
1612 t.setDaemon(true);
1613 return t;
1614 });
1615 stpe.setRemoveOnCancelPolicy(true);
1616 schedulers[i] = stpe;
1617 }
1618 return schedulers;
1619 }
1620 }
1621
1622 /**
1623 * Schedule virtual threads that are ready to be scheduled after they blocked on
1624 * monitor enter.
1625 */
1626 private static void unblockVirtualThreads() {
1627 while (true) {
1628 VirtualThread vthread = takeVirtualThreadListToUnblock();
1629 while (vthread != null) {
1630 assert vthread.onWaitingList;
1631 VirtualThread nextThread = vthread.next;
1632
1633 // remove from list and unblock
1634 vthread.next = null;
1635 boolean changed = vthread.compareAndSetOnWaitingList(true, false);
1636 assert changed;
1637 vthread.unblock();
1638
1639 vthread = nextThread;
1640 }
1641 }
1642 }
1643
1644 /**
1645 * Retrieves the list of virtual threads that are waiting to be unblocked, waiting
1646 * if necessary until a list of one or more threads becomes available.
1647 */
1648 private static native VirtualThread takeVirtualThreadListToUnblock();
1649
1650 static {
1651 var unblocker = InnocuousThread.newThread("VirtualThread-unblocker",
1652 VirtualThread::unblockVirtualThreads);
1653 unblocker.setDaemon(true);
1654 unblocker.start();
1655 }
1656 }