1 /*
2 * Copyright (c) 2018, 2025, 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.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
98 * TIMED_PARKING -> TIMED_PARKED // cont.yield successful, timed-parked
99 * TIMED_PARKING -> TIMED_PINNED // cont.yield failed, timed-parked on carrier
100 * TIMED_PARKED -> UNPARKED // unparked, may be scheduled to continue
101 * TIMED_PINNED -> RUNNING // unparked, continue execution on same carrier
102 *
103 * RUNNING -> BLOCKING // blocking on monitor enter
104 * BLOCKING -> BLOCKED // blocked on monitor enter
105 * BLOCKED -> UNBLOCKED // unblocked, may be scheduled to continue
106 * UNBLOCKED -> RUNNING // continue execution after blocked on monitor enter
107 *
108 * RUNNING -> WAITING // transitional state during wait on monitor
109 * WAITING -> WAIT // waiting on monitor
110 * WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner
111 * WAIT -> UNBLOCKED // timed-out/interrupted
112 *
113 * RUNNING -> TIMED_WAITING // transition state during timed-waiting on monitor
114 * TIMED_WAITING -> TIMED_WAIT // timed-waiting on monitor
115 * TIMED_WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner
116 * TIMED_WAIT -> UNBLOCKED // timed-out/interrupted
117 *
118 * RUNNING -> YIELDING // Thread.yield
119 * YIELDING -> YIELDED // cont.yield successful, may be scheduled to continue
120 * YIELDING -> RUNNING // cont.yield failed
121 * YIELDED -> RUNNING // continue execution after Thread.yield
122 */
123 private static final int NEW = 0;
124 private static final int STARTED = 1;
125 private static final int RUNNING = 2; // runnable-mounted
126
127 // untimed and timed parking
128 private static final int PARKING = 3;
129 private static final int PARKED = 4; // unmounted
130 private static final int PINNED = 5; // mounted
131 private static final int TIMED_PARKING = 6;
132 private static final int TIMED_PARKED = 7; // unmounted
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);
252 } finally {
253 vthread.startFinalTransition();
254 }
255 }
256 };
257 }
258 }
259
260 /**
261 * Runs or continues execution on the current thread. The virtual thread is mounted
262 * on the current thread before the task runs or continues. It unmounts when the
263 * task completes or yields.
264 */
265 @ChangesCurrentThread // allow mount/unmount to be inlined
266 private void runContinuation() {
267 // the carrier must be a platform thread
268 if (Thread.currentThread().isVirtual()) {
269 throw new WrongThreadException();
270 }
271
272 // set state to RUNNING
273 int initialState = state();
274 if (initialState == STARTED || initialState == UNPARKED
275 || initialState == UNBLOCKED || initialState == YIELDED) {
276 // newly started or continue after parking/blocking/Thread.yield
277 if (!compareAndSetState(initialState, RUNNING)) {
278 return;
279 }
280 // consume permit when continuing after parking or blocking. If continue
281 // after a timed-park or timed-wait then the timeout task is cancelled.
282 if (initialState == UNPARKED) {
283 cancelTimeoutTask();
284 setParkPermit(false);
285 } else if (initialState == UNBLOCKED) {
286 cancelTimeoutTask();
287 blockPermit = false;
288 }
289 } else {
290 // not runnable
291 return;
292 }
293
294 mount();
295 try {
296 cont.run();
297 } finally {
298 unmount();
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;
461
462 // emit JFR event if enabled
463 if (VirtualThreadStartEvent.isTurnedOn()) {
464 var event = new VirtualThreadStartEvent();
465 event.javaThreadId = threadId();
466 event.commit();
467 }
468
469 Object bindings = Thread.scopedValueBindings();
470 try {
471 runWith(bindings, task);
472 } catch (Throwable exc) {
473 dispatchUncaughtException(exc);
474 } finally {
475 // pop any remaining scopes from the stack, this may block
476 StackableScope.popAll();
477
478 // emit JFR event if enabled
479 if (VirtualThreadEndEvent.isTurnedOn()) {
480 var event = new VirtualThreadEndEvent();
481 event.javaThreadId = threadId();
482 event.commit();
483 }
484 }
485 }
486
487 /**
488 * Mounts this virtual thread onto the current platform thread. On
489 * return, the current thread is the virtual thread.
490 */
491 @ChangesCurrentThread
492 @ReservedStackAccess
493 private void mount() {
494 startTransition(/*is_mount*/true);
495 // We assume following volatile accesses provide equivalent
496 // of acquire ordering, otherwise we need U.loadFence() here.
497
498 // sets the carrier thread
499 Thread carrier = Thread.currentCarrierThread();
500 setCarrierThread(carrier);
501
502 // sync up carrier thread interrupted status if needed
503 if (interrupted) {
504 carrier.setInterrupt();
505 } else if (carrier.isInterrupted()) {
506 synchronized (interruptLock) {
507 // need to recheck interrupted status
508 if (!interrupted) {
509 carrier.clearInterrupt();
510 }
511 }
512 }
513
514 // set Thread.currentThread() to return this virtual thread
515 carrier.setCurrentThread(this);
516 }
517
518 /**
519 * Unmounts this virtual thread from the carrier. On return, the
520 * current thread is the current platform thread.
521 */
522 @ChangesCurrentThread
523 @ReservedStackAccess
524 private void unmount() {
525 assert !Thread.holdsLock(interruptLock);
526
527 // set Thread.currentThread() to return the platform thread
528 Thread carrier = this.carrierThread;
529 carrier.setCurrentThread(carrier);
530
531 // break connection to carrier thread, synchronized with interrupt
532 synchronized (interruptLock) {
533 setCarrierThread(null);
534 }
535 carrier.clearInterrupt();
536
537 // We assume previous volatile accesses provide equivalent
538 // of release ordering, otherwise we need U.storeFence() here.
539 endTransition(/*is_mount*/false);
540 }
541
542 /**
543 * Invokes Continuation.yield, notifying JVMTI (if enabled) to hide frames until
544 * the continuation continues.
545 */
546 @Hidden
547 private boolean yieldContinuation() {
548 startTransition(/*is_mount*/false);
549 try {
550 return Continuation.yield(VTHREAD_SCOPE);
551 } finally {
552 endTransition(/*is_mount*/true);
553 }
554 }
555
556 /**
557 * Invoked in the context of the carrier thread after the Continuation yields when
558 * parking, blocking on monitor enter, Object.wait, or Thread.yield.
559 */
560 private void afterYield() {
561 assert carrierThread == null;
562
563 // re-adjust parallelism if the virtual thread yielded when compensating
564 if (currentThread() instanceof CarrierThread ct) {
565 ct.endBlocking();
566 }
567
568 int s = state();
569
570 // LockSupport.park/parkNanos
571 if (s == PARKING || s == TIMED_PARKING) {
572 int newState;
573 if (s == PARKING) {
574 setState(newState = PARKED);
575 } else {
576 // schedule unpark
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) {
618 int newState;
619 boolean interruptible = interruptibleWait;
620 if (s == WAITING) {
621 setState(newState = WAIT);
622 } else {
623 // For timed-wait, a timeout task is scheduled to execute. The timeout
624 // task will change the thread state to UNBLOCKED and submit the thread
625 // to the scheduler. A sequence number is used to ensure that the timeout
626 // task only unblocks the thread for this timed-wait. We synchronize with
627 // the timeout task to coordinate access to the sequence number and to
628 // ensure the timeout task doesn't execute until the thread has got to
629 // the TIMED_WAIT state.
630 long timeout = this.timeout;
631 assert timeout > 0;
632 synchronized (timedWaitLock()) {
633 byte seqNo = ++timedWaitSeqNo;
634 timeoutTask = schedule(() -> waitTimeoutExpired(seqNo), timeout, MILLISECONDS);
635 setState(newState = TIMED_WAIT);
636 }
637 }
638
639 // may have been notified while in transition to wait state
640 if (notified && compareAndSetState(newState, BLOCKED)) {
641 // may have even been unblocked already
642 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
643 submitRunContinuation();
644 }
645 return;
646 }
647
648 // may have been interrupted while in transition to wait state
649 if (interruptible && interrupted && compareAndSetState(newState, UNBLOCKED)) {
650 submitRunContinuation();
651 return;
652 }
653 return;
654 }
655
656 assert false;
657 }
658
659 /**
660 * Invoked after the continuation completes.
661 */
662 private void afterDone() {
663 afterDone(true);
664 }
665
666 /**
667 * Invoked after the continuation completes (or start failed). Sets the thread
668 * state to TERMINATED and notifies anyone waiting for the thread to terminate.
669 *
670 * @param notifyContainer true if its container should be notified
671 */
672 private void afterDone(boolean notifyContainer) {
673 assert carrierThread == null;
674 setState(TERMINATED);
675
676 // notify anyone waiting for this virtual thread to terminate
677 CountDownLatch termination = this.termination;
678 if (termination != null) {
679 assert termination.getCount() == 1;
680 termination.countDown();
681 }
682
683 // notify container
684 if (notifyContainer) {
685 threadContainer().remove(this);
686 }
687
688 // clear references to thread locals
689 clearReferences();
690 }
691
692 /**
693 * Schedules this {@code VirtualThread} to execute.
694 *
695 * @throws IllegalStateException if the container is shutdown or closed
696 * @throws IllegalThreadStateException if the thread has already been started
697 * @throws RejectedExecutionException if the scheduler cannot accept a task
698 */
699 @Override
700 void start(ThreadContainer container) {
701 if (!compareAndSetState(NEW, STARTED)) {
702 throw new IllegalThreadStateException("Already started");
703 }
704
705 // bind thread to container
706 assert threadContainer() == null;
707 setThreadContainer(container);
708
709 // start thread
710 boolean addedToContainer = false;
711 boolean started = false;
712 try {
713 container.add(this); // may throw
714 addedToContainer = true;
715
716 // scoped values may be inherited
717 inheritScopedValueBindings(container);
718
719 // submit task to run thread, using externalSubmit if possible
720 externalSubmitRunContinuationOrThrow();
721 started = true;
722 } finally {
723 if (!started) {
724 afterDone(addedToContainer);
725 }
726 }
727 }
728
729 @Override
730 public void start() {
731 start(ThreadContainers.root());
732 }
733
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 */
824 private void parkOnCarrierThread(boolean timed, long nanos) {
825 assert state() == RUNNING;
826
827 setState(timed ? TIMED_PINNED : PINNED);
828 try {
829 if (!parkPermit) {
830 if (!timed) {
831 U.park(false, 0);
832 } else if (nanos > 0) {
833 U.park(false, nanos);
834 }
835 }
836 } finally {
837 setState(RUNNING);
838 }
839
840 // consume parking permit
841 setParkPermit(false);
842
843 // JFR jdk.VirtualThreadPinned event
844 postPinnedEvent("LockSupport.park");
845 }
846
847 /**
848 * Call into VM when pinned to record a JFR jdk.VirtualThreadPinned event.
849 * Recording the event in the VM avoids having JFR event recorded in Java
850 * with the same name, but different ID, to events recorded by the VM.
851 */
852 @Hidden
853 private static native void postPinnedEvent(String op);
854
855 /**
856 * Re-enables this virtual thread for scheduling. If this virtual thread is parked
857 * then its task is scheduled to continue, otherwise its next call to {@code park} or
858 * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block.
859 * @throws RejectedExecutionException if the scheduler cannot accept a task
860 */
861 @Override
862 void unpark() {
863 if (!getAndSetParkPermit(true) && currentThread() != this) {
864 int s = state();
865
866 // unparked while parked
867 if ((s == PARKED || s == TIMED_PARKED) && compareAndSetState(s, UNPARKED)) {
868 submitRunContinuation();
869 return;
870 }
871
872 // unparked while parked when pinned
873 if (s == PINNED || s == TIMED_PINNED) {
874 // unpark carrier thread when pinned
875 disableSuspendAndPreempt();
876 try {
877 synchronized (carrierThreadAccessLock()) {
878 Thread carrier = carrierThread;
879 if (carrier != null && ((s = state()) == PINNED || s == TIMED_PINNED)) {
880 U.unpark(carrier);
881 }
882 }
883 } finally {
884 enableSuspendAndPreempt();
885 }
886 return;
887 }
888 }
889 }
890
891 /**
892 * Invoked by unblocker thread to unblock this virtual thread.
893 */
894 private void unblock() {
895 assert !Thread.currentThread().isVirtual();
896 blockPermit = true;
897 if (state() == BLOCKED && compareAndSetState(BLOCKED, UNBLOCKED)) {
898 submitRunContinuation();
899 }
900 }
901
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 }
963
964 /**
965 * Sleep the current thread for the given sleep time (in nanoseconds). If
966 * nanos is 0 then the thread will attempt to yield.
967 *
968 * @implNote This implementation parks the thread for the given sleeping time
969 * and will therefore be observed in PARKED state during the sleep. Parking
970 * will consume the parking permit so this method makes available the parking
971 * permit after the sleep. This may be observed as a spurious, but benign,
972 * wakeup when the thread subsequently attempts to park.
973 *
974 * @param nanos the maximum number of nanoseconds to sleep
975 * @throws InterruptedException if interrupted while sleeping
976 */
977 void sleepNanos(long nanos) throws InterruptedException {
978 assert Thread.currentThread() == this && nanos >= 0;
979 if (getAndClearInterrupt())
980 throw new InterruptedException();
981 if (nanos == 0) {
982 tryYield();
983 } else {
984 // park for the sleep time
985 try {
986 long remainingNanos = nanos;
987 long startNanos = System.nanoTime();
988 while (remainingNanos > 0) {
989 parkNanos(remainingNanos);
990 if (getAndClearInterrupt()) {
991 throw new InterruptedException();
992 }
993 remainingNanos = nanos - (System.nanoTime() - startNanos);
994 }
995 } finally {
996 // may have been unparked while sleeping
997 setParkPermit(true);
998 }
999 }
1000 }
1001
1002 /**
1003 * Waits up to {@code nanos} nanoseconds for this virtual thread to terminate.
1004 * A timeout of {@code 0} means to wait forever.
1005 *
1006 * @throws InterruptedException if interrupted while waiting
1007 * @return true if the thread has terminated
1008 */
1009 boolean joinNanos(long nanos) throws InterruptedException {
1010 if (state() == TERMINATED)
1011 return true;
1012
1013 // ensure termination object exists, then re-check state
1014 CountDownLatch termination = getTermination();
1015 if (state() == TERMINATED)
1016 return true;
1017
1018 // wait for virtual thread to terminate
1019 if (nanos == 0) {
1020 termination.await();
1021 } else {
1022 boolean terminated = termination.await(nanos, NANOSECONDS);
1023 if (!terminated) {
1024 // waiting time elapsed
1025 return false;
1026 }
1027 }
1028 assert state() == TERMINATED;
1029 return true;
1030 }
1031
1032 @Override
1033 void blockedOn(Interruptible b) {
1034 disableSuspendAndPreempt();
1035 try {
1036 super.blockedOn(b);
1037 } finally {
1038 enableSuspendAndPreempt();
1039 }
1040 }
1041
1042 @Override
1043 public void interrupt() {
1044 if (Thread.currentThread() != this) {
1045 // if current thread is a virtual thread then prevent it from being
1046 // suspended or unmounted when entering or holding interruptLock
1047 Interruptible blocker;
1048 disableSuspendAndPreempt();
1049 try {
1050 synchronized (interruptLock) {
1051 interrupted = true;
1052 blocker = nioBlocker();
1053 if (blocker != null) {
1054 blocker.interrupt(this);
1055 }
1056
1057 // interrupt carrier thread if mounted
1058 Thread carrier = carrierThread;
1059 if (carrier != null) carrier.setInterrupt();
1060 }
1061 } finally {
1062 enableSuspendAndPreempt();
1063 }
1064
1065 // notify blocker after releasing interruptLock
1066 if (blocker != null) {
1067 blocker.postInterrupt();
1068 }
1069
1070 // make available parking permit, unpark thread if parked
1071 unpark();
1072
1073 // if thread is waiting in Object.wait then schedule to try to reenter
1074 int s = state();
1075 if ((s == WAIT || s == TIMED_WAIT) && compareAndSetState(s, UNBLOCKED)) {
1076 submitRunContinuation();
1077 }
1078
1079 } else {
1080 interrupted = true;
1081 carrierThread.setInterrupt();
1082 setParkPermit(true);
1083 }
1084 }
1085
1086 @Override
1087 public boolean isInterrupted() {
1088 return interrupted;
1089 }
1090
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()) {
1133 Thread carrierThread = this.carrierThread;
1134 if (carrierThread != null) {
1135 return carrierThread.threadState();
1136 }
1137 }
1138 } finally {
1139 enableSuspendAndPreempt();
1140 }
1141 }
1142 // runnable, mounted
1143 return Thread.State.RUNNABLE;
1144 case PARKING:
1145 case TIMED_PARKING:
1146 case WAITING:
1147 case TIMED_WAITING:
1148 case YIELDING:
1149 // runnable, in transition
1150 return Thread.State.RUNNABLE;
1151 case PARKED:
1152 case PINNED:
1153 case WAIT:
1154 return Thread.State.WAITING;
1155 case TIMED_PARKED:
1156 case TIMED_PINNED:
1157 case TIMED_WAIT:
1158 return Thread.State.TIMED_WAITING;
1159 case BLOCKING:
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);
1279 }
1280 } finally {
1281 enableSuspendAndPreempt();
1282 }
1283 }
1284
1285 // add virtual thread state when not mounted
1286 if (!mounted) {
1287 String stateAsString = threadState().toString();
1288 sb.append(stateAsString.toLowerCase(Locale.ROOT));
1289 }
1290
1291 return sb.toString();
1292 }
1293
1294 /**
1295 * Appends the carrier state and thread name to the string buffer if mounted.
1296 * @return true if mounted, false if not mounted
1297 */
1298 private boolean appendCarrierInfo(StringBuilder sb) {
1299 assert Thread.currentThread() == this || Thread.holdsLock(carrierThreadAccessLock());
1300 Thread carrier = carrierThread;
1301 if (carrier != null) {
1302 String stateAsString = carrier.threadState().toString();
1303 sb.append(stateAsString.toLowerCase(Locale.ROOT));
1304 sb.append('@');
1305 sb.append(carrier.getName());
1306 return true;
1307 } else {
1308 return false;
1309 }
1310 }
1311
1312 @Override
1313 public int hashCode() {
1314 return (int) threadId();
1315 }
1316
1317 @Override
1318 public boolean equals(Object obj) {
1319 return obj == this;
1320 }
1321
1322 /**
1323 * Returns the termination object, creating it if needed.
1324 */
1325 private CountDownLatch getTermination() {
1326 CountDownLatch termination = this.termination;
1327 if (termination == null) {
1328 termination = new CountDownLatch(1);
1329 if (!U.compareAndSetReference(this, TERMINATION, null, termination)) {
1330 termination = this.termination;
1331 }
1332 }
1333 return termination;
1334 }
1335
1336 /**
1337 * Returns the lock object to synchronize on when accessing carrierThread.
1338 * The lock prevents carrierThread from being reset to null during unmount.
1339 */
1340 private Object carrierThreadAccessLock() {
1341 // return interruptLock as unmount has to coordinate with interrupt
1342 return interruptLock;
1343 }
1344
1345 /**
1346 * Returns a lock object for coordinating timed-wait setup and timeout handling.
1347 */
1348 private Object timedWaitLock() {
1349 // use this object for now to avoid the overhead of introducing another lock
1350 return runContinuation;
1351 }
1352
1353 /**
1354 * Disallow the current thread be suspended or preempted.
1355 */
1356 private void disableSuspendAndPreempt() {
1357 notifyJvmtiDisableSuspend(true);
1358 Continuation.pin();
1359 }
1360
1361 /**
1362 * Allow the current thread be suspended or preempted.
1363 */
1364 private void enableSuspendAndPreempt() {
1365 Continuation.unpin();
1366 notifyJvmtiDisableSuspend(false);
1367 }
1368
1369 // -- wrappers for get/set of state, parking permit, and carrier thread --
1370
1371 private int state() {
1372 return state; // volatile read
1373 }
1374
1375 private void setState(int newValue) {
1376 state = newValue; // volatile write
1377 }
1378
1379 private boolean compareAndSetState(int expectedValue, int newValue) {
1380 return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1381 }
1382
1383 private boolean compareAndSetOnWaitingList(boolean expectedValue, boolean newValue) {
1384 return U.compareAndSetBoolean(this, ON_WAITING_LIST, expectedValue, newValue);
1385 }
1386
1387 private void setParkPermit(boolean newValue) {
1388 if (parkPermit != newValue) {
1389 parkPermit = newValue;
1390 }
1391 }
1392
1393 private boolean getAndSetParkPermit(boolean newValue) {
1394 if (parkPermit != newValue) {
1395 return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1396 } else {
1397 return newValue;
1398 }
1399 }
1400
1401 private void setCarrierThread(Thread carrier) {
1402 // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1403 this.carrierThread = carrier;
1404 }
1405
1406 // The following four methods notify the VM when a "transition" starts and ends.
1407 // A "mount transition" embodies the steps to transfer control from a platform
1408 // thread to a virtual thread, changing the thread identity, and starting or
1409 // resuming the virtual thread's continuation on the carrier.
1410 // An "unmount transition" embodies the steps to transfer control from a virtual
1411 // thread to its carrier, suspending the virtual thread's continuation, and
1412 // restoring the thread identity to the platform thread.
1413 // The notifications to the VM are necessary in order to coordinate with functions
1414 // (JVMTI mostly) that disable transitions for one or all virtual threads. Starting
1415 // a transition may block if transitions are disabled. Ending a transition may
1416 // notify a thread that is waiting to disable transitions. The notifications are
1417 // also used to post JVMTI events for virtual thread start and end.
1418
1419 @IntrinsicCandidate
1420 @JvmtiMountTransition
1421 private native void endFirstTransition();
1422
1423 @IntrinsicCandidate
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() {
1503 String propName = "jdk.virtualThreadScheduler.timerQueues";
1504 String propValue = System.getProperty(propName);
1505 int queueCount;
1506 if (propValue != null) {
1507 queueCount = Integer.parseInt(propValue);
1508 if (queueCount != Integer.highestOneBit(queueCount)) {
1509 throw new RuntimeException("Value of " + propName + " must be power of 2");
1510 }
1511 } else {
1512 int ncpus = Runtime.getRuntime().availableProcessors();
1513 queueCount = Math.max(Integer.highestOneBit(ncpus / 4), 1);
1514 }
1515 var schedulers = new ScheduledExecutorService[queueCount];
1516 for (int i = 0; i < queueCount; i++) {
1517 ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor)
1518 Executors.newScheduledThreadPool(1, task -> {
1519 Thread t = InnocuousThread.newThread("VirtualThread-unparker", task);
1520 t.setDaemon(true);
1521 return t;
1522 });
1523 stpe.setRemoveOnCancelPolicy(true);
1524 schedulers[i] = stpe;
1525 }
1526 return schedulers;
1527 }
1528 }
1529
1530 /**
1531 * Schedule virtual threads that are ready to be scheduled after they blocked on
1532 * monitor enter.
1533 */
1534 private static void unblockVirtualThreads() {
1535 while (true) {
1536 VirtualThread vthread = takeVirtualThreadListToUnblock();
1537 while (vthread != null) {
1538 assert vthread.onWaitingList;
1539 VirtualThread nextThread = vthread.next;
1540
1541 // remove from list and unblock
1542 vthread.next = null;
1543 boolean changed = vthread.compareAndSetOnWaitingList(true, false);
1544 assert changed;
1545 vthread.unblock();
1546
1547 vthread = nextThread;
1548 }
1549 }
1550 }
1551
1552 /**
1553 * Retrieves the list of virtual threads that are waiting to be unblocked, waiting
1554 * if necessary until a list of one or more threads becomes available.
1555 */
1556 private static native VirtualThread takeVirtualThreadListToUnblock();
1557
1558 static {
1559 var unblocker = InnocuousThread.newThread("VirtualThread-unblocker",
1560 VirtualThread::unblockVirtualThreads);
1561 unblocker.setDaemon(true);
1562 unblocker.start();
1563 }
1564 }