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;
133 private static final int TIMED_PINNED = 8; // mounted
134 private static final int UNPARKED = 9; // unmounted but runnable
135
136 // Thread.yield
137 private static final int YIELDING = 10;
138 private static final int YIELDED = 11; // unmounted but runnable
139
140 // monitor enter
141 private static final int BLOCKING = 12;
142 private static final int BLOCKED = 13; // unmounted
143 private static final int UNBLOCKED = 14; // unmounted but runnable
144
145 // monitor wait/timed-wait
146 private static final int WAITING = 15;
147 private static final int WAIT = 16; // waiting in Object.wait
148 private static final int TIMED_WAITING = 17;
149 private static final int TIMED_WAIT = 18; // waiting in timed-Object.wait
150
151 private static final int TERMINATED = 99; // final state
152
153 // can be suspended from scheduling when unmounted
154 private static final int SUSPENDED = 1 << 8;
155
156 // parking permit made available by LockSupport.unpark
157 private volatile boolean parkPermit;
158
159 // blocking permit made available by unblocker thread when another thread exits monitor
160 private volatile boolean blockPermit;
161
162 // true when on the list of virtual threads waiting to be unblocked
163 private volatile boolean onWaitingList;
164
165 // next virtual thread on the list of virtual threads waiting to be unblocked
166 private volatile VirtualThread next;
167
168 // notified by Object.notify/notifyAll while waiting in Object.wait
169 private volatile boolean notified;
170
171 // true when waiting in Object.wait, false for VM internal uninterruptible Object.wait
172 private volatile boolean interruptibleWait;
173
174 // timed-wait support
175 private byte timedWaitSeqNo;
176
177 // timeout for timed-park and timed-wait, only accessed on current/carrier thread
178 private long timeout;
179
180 // timer task for timed-park and timed-wait, only accessed on current/carrier thread
181 private Future<?> timeoutTask;
182
183 // carrier thread when mounted, accessed by VM
184 private volatile Thread carrierThread;
185
186 // termination object when joining, created lazily if needed
187 private volatile CountDownLatch termination;
188
189 /**
190 * Returns the default scheduler.
191 */
192 static Executor defaultScheduler() {
193 return DEFAULT_SCHEDULER;
194 }
195
196 /**
197 * Returns the continuation scope used for virtual threads.
198 */
199 static ContinuationScope continuationScope() {
200 return VTHREAD_SCOPE;
201 }
202
203 /**
204 * Creates a new {@code VirtualThread} to run the given task with the given
205 * scheduler. If the given scheduler is {@code null} and the current thread
206 * is a platform thread then the newly created virtual thread will use the
207 * default scheduler. If given scheduler is {@code null} and the current
208 * thread is a virtual thread then the current thread's scheduler is used.
209 *
210 * @param scheduler the scheduler or null
211 * @param name thread name
212 * @param characteristics characteristics
213 * @param task the task to execute
214 */
215 VirtualThread(Executor scheduler, String name, int characteristics, Runnable task) {
216 super(name, characteristics, /*bound*/ false);
217 Objects.requireNonNull(task);
218
219 // choose scheduler if not specified
220 if (scheduler == null) {
221 Thread parent = Thread.currentThread();
222 if (parent instanceof VirtualThread vparent) {
223 scheduler = vparent.scheduler;
224 } else {
225 scheduler = DEFAULT_SCHEDULER;
226 }
227 }
228
229 this.scheduler = scheduler;
230 this.cont = new VThreadContinuation(this, task);
231 this.runContinuation = this::runContinuation;
232 }
233
234 /**
235 * The continuation that a virtual thread executes.
236 */
237 private static class VThreadContinuation extends Continuation {
238 VThreadContinuation(VirtualThread vthread, Runnable task) {
239 super(VTHREAD_SCOPE, wrap(vthread, task));
240 }
241 @Override
242 protected void onPinned(Continuation.Pinned reason) {
243 }
244 private static Runnable wrap(VirtualThread vthread, Runnable task) {
245 return new Runnable() {
246 @Hidden
247 @JvmtiHideEvents
248 public void run() {
249 vthread.endFirstTransition();
250 try {
251 vthread.run(task);
299 if (cont.isDone()) {
300 afterDone();
301 } else {
302 afterYield();
303 }
304 }
305 }
306
307 /**
308 * Cancel timeout task when continuing after timed-park or timed-wait.
309 * The timeout task may be executing, or may have already completed.
310 */
311 private void cancelTimeoutTask() {
312 if (timeoutTask != null) {
313 timeoutTask.cancel(false);
314 timeoutTask = null;
315 }
316 }
317
318 /**
319 * Submits the given task to the given executor. If the scheduler is a
320 * ForkJoinPool then the task is first adapted to a ForkJoinTask.
321 */
322 private void submit(Executor executor, Runnable task) {
323 if (executor instanceof ForkJoinPool pool) {
324 pool.submit(ForkJoinTask.adapt(task));
325 } else {
326 executor.execute(task);
327 }
328 }
329
330 /**
331 * Submits the runContinuation task to the scheduler. For the default scheduler,
332 * and calling it on a worker thread, the task will be pushed to the local queue,
333 * otherwise it will be pushed to an external submission queue.
334 * @param scheduler the scheduler
335 * @param retryOnOOME true to retry indefinitely if OutOfMemoryError is thrown
336 * @throws RejectedExecutionException
337 */
338 private void submitRunContinuation(Executor scheduler, boolean retryOnOOME) {
339 boolean done = false;
340 while (!done) {
341 try {
342 // Pin the continuation to prevent the virtual thread from unmounting
343 // when submitting a task. For the default scheduler this ensures that
344 // the carrier doesn't change when pushing a task. For other schedulers
345 // it avoids deadlock that could arise due to carriers and virtual
346 // threads contending for a lock.
347 if (currentThread().isVirtual()) {
348 Continuation.pin();
349 try {
350 submit(scheduler, runContinuation);
351 } finally {
352 Continuation.unpin();
353 }
354 } else {
355 submit(scheduler, runContinuation);
356 }
357 done = true;
358 } catch (RejectedExecutionException ree) {
359 submitFailed(ree);
360 throw ree;
361 } catch (OutOfMemoryError e) {
362 if (retryOnOOME) {
363 U.park(false, 100_000_000); // 100ms
364 } else {
365 throw e;
366 }
367 }
368 }
369 }
370
371 /**
372 * Submits the runContinuation task to the given scheduler as an external submit.
373 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
374 * @throws RejectedExecutionException
375 * @see ForkJoinPool#externalSubmit(ForkJoinTask)
376 */
377 private void externalSubmitRunContinuation(ForkJoinPool pool) {
378 assert Thread.currentThread() instanceof CarrierThread;
379 try {
380 pool.externalSubmit(ForkJoinTask.adapt(runContinuation));
381 } catch (RejectedExecutionException ree) {
382 submitFailed(ree);
383 throw ree;
384 } catch (OutOfMemoryError e) {
385 submitRunContinuation(pool, true);
386 }
387 }
388
389 /**
390 * Submits the runContinuation task to the scheduler. For the default scheduler,
391 * and calling it on a worker thread, the task will be pushed to the local queue,
392 * otherwise it will be pushed to an external submission queue.
393 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
394 * @throws RejectedExecutionException
395 */
396 private void submitRunContinuation() {
397 submitRunContinuation(scheduler, true);
398 }
399
400 /**
401 * Lazy submit the runContinuation task if invoked on a carrier thread and its local
402 * queue is empty. If not empty, or invoked by another thread, then this method works
403 * like submitRunContinuation and just submits the task to the scheduler.
404 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
405 * @throws RejectedExecutionException
406 * @see ForkJoinPool#lazySubmit(ForkJoinTask)
407 */
408 private void lazySubmitRunContinuation() {
409 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
410 ForkJoinPool pool = ct.getPool();
411 try {
412 pool.lazySubmit(ForkJoinTask.adapt(runContinuation));
413 } catch (RejectedExecutionException ree) {
414 submitFailed(ree);
415 throw ree;
416 } catch (OutOfMemoryError e) {
417 submitRunContinuation();
418 }
419 } else {
420 submitRunContinuation();
421 }
422 }
423
424 /**
425 * Submits the runContinuation task to the scheduler. For the default scheduler, and
426 * calling it a virtual thread that uses the default scheduler, the task will be
427 * pushed to an external submission queue. This method may throw OutOfMemoryError.
428 * @throws RejectedExecutionException
429 * @throws OutOfMemoryError
430 */
431 private void externalSubmitRunContinuationOrThrow() {
432 if (scheduler == DEFAULT_SCHEDULER && currentCarrierThread() instanceof CarrierThread ct) {
433 try {
434 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
435 } catch (RejectedExecutionException ree) {
436 submitFailed(ree);
437 throw ree;
438 }
439 } else {
440 submitRunContinuation(scheduler, false);
441 }
442 }
443
444 /**
445 * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
446 */
447 private void submitFailed(RejectedExecutionException ree) {
448 var event = new VirtualThreadSubmitFailedEvent();
449 if (event.isEnabled()) {
450 event.javaThreadId = threadId();
451 event.exceptionMessage = ree.getMessage();
452 event.commit();
453 }
454 }
455
456 /**
457 * Runs a task in the context of this virtual thread.
458 */
459 private void run(Runnable task) {
460 assert Thread.currentThread() == this && state == RUNNING;
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
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;
577 long timeout = this.timeout;
578 assert timeout > 0;
579 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS);
580 setState(newState = TIMED_PARKED);
581 }
582
583 // may have been unparked while parking
584 if (parkPermit && compareAndSetState(newState, UNPARKED)) {
585 // lazy submit if local queue is empty
586 lazySubmitRunContinuation();
587 }
588 return;
589 }
590
591 // Thread.yield
592 if (s == YIELDING) {
593 setState(YIELDED);
594
595 // external submit if there are no tasks in the local task queue
596 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
597 externalSubmitRunContinuation(ct.getPool());
598 } else {
599 submitRunContinuation();
600 }
601 return;
602 }
603
604 // blocking on monitorenter
605 if (s == BLOCKING) {
606 setState(BLOCKED);
607
608 // may have been unblocked while blocking
609 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
610 // lazy submit if local queue is empty
611 lazySubmitRunContinuation();
612 }
613 return;
614 }
615
616 // Object.wait
617 if (s == WAITING || s == TIMED_WAITING) {
734 @Override
735 public void run() {
736 // do nothing
737 }
738
739 /**
740 * Parks until unparked or interrupted. If already unparked then the parking
741 * permit is consumed and this method completes immediately (meaning it doesn't
742 * yield). It also completes immediately if the interrupted status is set.
743 */
744 @Override
745 void park() {
746 assert Thread.currentThread() == this;
747
748 // complete immediately if parking permit available or interrupted
749 if (getAndSetParkPermit(false) || interrupted)
750 return;
751
752 // park the thread
753 boolean yielded = false;
754 setState(PARKING);
755 try {
756 yielded = yieldContinuation();
757 } catch (OutOfMemoryError e) {
758 // park on carrier
759 } finally {
760 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
761 if (!yielded) {
762 assert state() == PARKING;
763 setState(RUNNING);
764 }
765 }
766
767 // park on the carrier thread when pinned
768 if (!yielded) {
769 parkOnCarrierThread(false, 0);
770 }
771 }
772
773 /**
774 * Parks up to the given waiting time or until unparked or interrupted.
775 * If already unparked then the parking permit is consumed and this method
776 * completes immediately (meaning it doesn't yield). It also completes immediately
777 * if the interrupted status is set or the waiting time is {@code <= 0}.
778 *
779 * @param nanos the maximum number of nanoseconds to wait.
780 */
781 @Override
782 void parkNanos(long nanos) {
783 assert Thread.currentThread() == this;
784
785 // complete immediately if parking permit available or interrupted
786 if (getAndSetParkPermit(false) || interrupted)
787 return;
788
789 // park the thread for the waiting time
790 if (nanos > 0) {
791 long startTime = System.nanoTime();
792
793 // park the thread, afterYield will schedule the thread to unpark
794 boolean yielded = false;
795 timeout = nanos;
796 setState(TIMED_PARKING);
797 try {
798 yielded = yieldContinuation();
799 } catch (OutOfMemoryError e) {
800 // park on carrier
801 } finally {
802 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
803 if (!yielded) {
804 assert state() == TIMED_PARKING;
805 setState(RUNNING);
806 }
807 }
808
809 // park on carrier thread for remaining time when pinned (or OOME)
810 if (!yielded) {
811 long remainingNanos = nanos - (System.nanoTime() - startTime);
812 parkOnCarrierThread(true, remainingNanos);
813 }
814 }
815 }
816
817 /**
818 * Parks the current carrier thread up to the given waiting time or until
819 * unparked or interrupted. If the virtual thread is interrupted then the
820 * interrupted status will be propagated to the carrier thread.
821 * @param timed true for a timed park, false for untimed
822 * @param nanos the waiting time in nanoseconds
823 */
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
1091 @Override
1092 boolean getAndClearInterrupt() {
1093 assert Thread.currentThread() == this;
1094 boolean oldValue = interrupted;
1095 if (oldValue) {
1096 disableSuspendAndPreempt();
1097 try {
1098 synchronized (interruptLock) {
1099 interrupted = false;
1100 carrierThread.clearInterrupt();
1101 }
1102 } finally {
1103 enableSuspendAndPreempt();
1104 }
1105 }
1106 return oldValue;
1107 }
1108
1109 @Override
1110 Thread.State threadState() {
1111 int s = state();
1112 switch (s & ~SUSPENDED) {
1113 case NEW:
1114 return Thread.State.NEW;
1115 case STARTED:
1116 // return NEW if thread container not yet set
1117 if (threadContainer() == null) {
1118 return Thread.State.NEW;
1119 } else {
1120 return Thread.State.RUNNABLE;
1121 }
1122 case UNPARKED:
1123 case UNBLOCKED:
1124 case YIELDED:
1125 // runnable, not mounted
1126 return Thread.State.RUNNABLE;
1127 case RUNNING:
1128 // if mounted then return state of carrier thread
1129 if (Thread.currentThread() != this) {
1130 disableSuspendAndPreempt();
1131 try {
1132 synchronized (carrierThreadAccessLock()) {
1160 case BLOCKED:
1161 return Thread.State.BLOCKED;
1162 case TERMINATED:
1163 return Thread.State.TERMINATED;
1164 default:
1165 throw new InternalError();
1166 }
1167 }
1168
1169 @Override
1170 boolean alive() {
1171 int s = state;
1172 return (s != NEW && s != TERMINATED);
1173 }
1174
1175 @Override
1176 boolean isTerminated() {
1177 return (state == TERMINATED);
1178 }
1179
1180 @Override
1181 StackTraceElement[] asyncGetStackTrace() {
1182 StackTraceElement[] stackTrace;
1183 do {
1184 stackTrace = (carrierThread != null)
1185 ? super.asyncGetStackTrace() // mounted
1186 : tryGetStackTrace(); // unmounted
1187 if (stackTrace == null) {
1188 Thread.yield();
1189 }
1190 } while (stackTrace == null);
1191 return stackTrace;
1192 }
1193
1194 /**
1195 * Returns the stack trace for this virtual thread if it is unmounted.
1196 * Returns null if the thread is mounted or in transition.
1197 */
1198 private StackTraceElement[] tryGetStackTrace() {
1199 int initialState = state() & ~SUSPENDED;
1200 switch (initialState) {
1201 case NEW, STARTED, TERMINATED -> {
1202 return new StackTraceElement[0]; // unmounted, empty stack
1203 }
1204 case RUNNING, PINNED, TIMED_PINNED -> {
1205 return null; // mounted
1206 }
1207 case PARKED, TIMED_PARKED, BLOCKED, WAIT, TIMED_WAIT -> {
1208 // unmounted, not runnable
1209 }
1210 case UNPARKED, UNBLOCKED, YIELDED -> {
1211 // unmounted, runnable
1212 }
1213 case PARKING, TIMED_PARKING, BLOCKING, YIELDING, WAITING, TIMED_WAITING -> {
1214 return null; // in transition
1215 }
1216 default -> throw new InternalError("" + initialState);
1217 }
1218
1219 // thread is unmounted, prevent it from continuing
1220 int suspendedState = initialState | SUSPENDED;
1221 if (!compareAndSetState(initialState, suspendedState)) {
1222 return null;
1223 }
1224
1225 // get stack trace and restore state
1226 StackTraceElement[] stack;
1227 try {
1228 stack = cont.getStackTrace();
1229 } finally {
1230 assert state == suspendedState;
1231 setState(initialState);
1232 }
1233 boolean resubmit = switch (initialState) {
1234 case UNPARKED, UNBLOCKED, YIELDED -> {
1235 // resubmit as task may have run while suspended
1236 yield true;
1237 }
1238 case PARKED, TIMED_PARKED -> {
1239 // resubmit if unparked while suspended
1240 yield parkPermit && compareAndSetState(initialState, UNPARKED);
1241 }
1242 case BLOCKED -> {
1243 // resubmit if unblocked while suspended
1244 yield blockPermit && compareAndSetState(BLOCKED, UNBLOCKED);
1245 }
1246 case WAIT, TIMED_WAIT -> {
1247 // resubmit if notified or interrupted while waiting (Object.wait)
1248 // waitTimeoutExpired will retry if the timed expired when suspended
1249 yield (notified || interrupted) && compareAndSetState(initialState, UNBLOCKED);
1250 }
1251 default -> throw new InternalError();
1252 };
1253 if (resubmit) {
1254 submitRunContinuation();
1255 }
1256 return stack;
1257 }
1258
1259 @Override
1260 public String toString() {
1261 StringBuilder sb = new StringBuilder("VirtualThread[#");
1262 sb.append(threadId());
1263 String name = getName();
1264 if (!name.isEmpty()) {
1265 sb.append(",");
1266 sb.append(name);
1267 }
1268 sb.append("]/");
1269
1270 // add the carrier state and thread name when mounted
1271 boolean mounted;
1272 if (Thread.currentThread() == this) {
1273 mounted = appendCarrierInfo(sb);
1274 } else {
1275 disableSuspendAndPreempt();
1276 try {
1277 synchronized (carrierThreadAccessLock()) {
1278 mounted = appendCarrierInfo(sb);
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() {
|
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package java.lang;
26
27 import java.lang.invoke.MethodHandles;
28 import java.lang.invoke.VarHandle;
29 import java.lang.reflect.Constructor;
30 import java.util.Locale;
31 import java.util.Objects;
32 import java.util.concurrent.CountDownLatch;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ForkJoinPool;
35 import java.util.concurrent.ForkJoinTask;
36 import java.util.concurrent.Future;
37 import java.util.concurrent.RejectedExecutionException;
38 import java.util.concurrent.ScheduledExecutorService;
39 import java.util.concurrent.ScheduledThreadPoolExecutor;
40 import java.util.concurrent.TimeUnit;
41 import jdk.internal.event.VirtualThreadEndEvent;
42 import jdk.internal.event.VirtualThreadParkEvent;
43 import jdk.internal.event.VirtualThreadStartEvent;
44 import jdk.internal.event.VirtualThreadSubmitFailedEvent;
45 import jdk.internal.invoke.MhUtil;
46 import jdk.internal.misc.CarrierThread;
47 import jdk.internal.misc.InnocuousThread;
48 import jdk.internal.misc.Unsafe;
49 import jdk.internal.vm.Continuation;
50 import jdk.internal.vm.ContinuationScope;
51 import jdk.internal.vm.StackableScope;
52 import jdk.internal.vm.ThreadContainer;
53 import jdk.internal.vm.ThreadContainers;
54 import jdk.internal.vm.annotation.ChangesCurrentThread;
55 import jdk.internal.vm.annotation.Hidden;
56 import jdk.internal.vm.annotation.IntrinsicCandidate;
57 import jdk.internal.vm.annotation.JvmtiHideEvents;
58 import jdk.internal.vm.annotation.JvmtiMountTransition;
59 import jdk.internal.vm.annotation.ReservedStackAccess;
60 import sun.nio.ch.Interruptible;
61 import static java.util.concurrent.TimeUnit.*;
62
63 /**
64 * A thread that is scheduled by the Java virtual machine rather than the operating system.
65 */
66 final class VirtualThread extends BaseVirtualThread {
67 private static final Unsafe U = Unsafe.getUnsafe();
68 private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
69
70 private static final BuiltinScheduler BUILTIN_SCHEDULER;
71 private static final VirtualThreadScheduler DEFAULT_SCHEDULER;
72 private static final VirtualThreadScheduler EXTERNAL_VIEW;
73 static {
74 // experimental
75 String propValue = System.getProperty("jdk.virtualThreadScheduler.implClass");
76 if (propValue != null) {
77 BuiltinScheduler builtinScheduler = createBuiltinScheduler(true);
78 VirtualThreadScheduler externalView = builtinScheduler.createExternalView();
79 VirtualThreadScheduler defaultScheduler = loadCustomScheduler(externalView, propValue);
80 BUILTIN_SCHEDULER = builtinScheduler;
81 DEFAULT_SCHEDULER = defaultScheduler;
82 EXTERNAL_VIEW = externalView;
83 } else {
84 var builtinScheduler = createBuiltinScheduler(false);
85 BUILTIN_SCHEDULER = builtinScheduler;
86 DEFAULT_SCHEDULER = builtinScheduler;
87 EXTERNAL_VIEW = builtinScheduler.createExternalView();
88 }
89 }
90
91 private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
92 private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
93 private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
94 private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
95 private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList");
96
97 // scheduler and continuation
98 private final VirtualThreadScheduler scheduler;
99 private final Continuation cont;
100 private final VirtualThreadTask runContinuation;
101
102 // virtual thread state, accessed by VM
103 private volatile int state;
104
105 /*
106 * Virtual thread state transitions:
107 *
108 * NEW -> STARTED // Thread.start, schedule to run
109 * STARTED -> TERMINATED // failed to start
110 * STARTED -> RUNNING // first run
111 * RUNNING -> TERMINATED // done
112 *
113 * RUNNING -> PARKING // Thread parking with LockSupport.park
114 * PARKING -> PARKED // cont.yield successful, parked indefinitely
115 * PARKED -> UNPARKED // unparked, may be scheduled to continue
116 * UNPARKED -> RUNNING // continue execution after park
117 *
118 * PARKING -> RUNNING // cont.yield failed, need to park on carrier
119 * RUNNING -> PINNED // park on carrier
120 * PINNED -> RUNNING // unparked, continue execution on same carrier
121 *
122 * RUNNING -> TIMED_PARKING // Thread parking with LockSupport.parkNanos
123 * TIMED_PARKING -> TIMED_PARKED // cont.yield successful, timed-parked
124 * TIMED_PARKED -> UNPARKED // unparked, may be scheduled to continue
125 *
126 * TIMED_PARKING -> RUNNING // cont.yield failed, need to park on carrier
127 * RUNNING -> TIMED_PINNED // park on carrier
128 * TIMED_PINNED -> RUNNING // unparked, continue execution on same carrier
129 *
130 * RUNNING -> BLOCKING // blocking on monitor enter
131 * BLOCKING -> BLOCKED // blocked on monitor enter
132 * BLOCKED -> UNBLOCKED // unblocked, may be scheduled to continue
133 * UNBLOCKED -> RUNNING // continue execution after blocked on monitor enter
134 *
135 * RUNNING -> WAITING // transitional state during wait on monitor
136 * WAITING -> WAIT // waiting on monitor
137 * WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner
138 * WAIT -> UNBLOCKED // interrupted
139 *
140 * RUNNING -> TIMED_WAITING // transition state during timed-waiting on monitor
141 * TIMED_WAITING -> TIMED_WAIT // timed-waiting on monitor
142 * TIMED_WAIT -> BLOCKED // notified, waiting to be unblocked by monitor owner
143 * TIMED_WAIT -> UNBLOCKED // timed-out/interrupted
144 *
145 * RUNNING -> YIELDING // Thread.yield
146 * YIELDING -> YIELDED // cont.yield successful, may be scheduled to continue
147 * YIELDING -> RUNNING // cont.yield failed
148 * YIELDED -> RUNNING // continue execution after Thread.yield
149 */
150 private static final int NEW = 0;
151 private static final int STARTED = 1;
152 private static final int RUNNING = 2; // runnable-mounted
153
154 // untimed and timed parking
155 private static final int PARKING = 3;
156 private static final int PARKED = 4; // unmounted
157 private static final int PINNED = 5; // mounted
158 private static final int TIMED_PARKING = 6;
160 private static final int TIMED_PINNED = 8; // mounted
161 private static final int UNPARKED = 9; // unmounted but runnable
162
163 // Thread.yield
164 private static final int YIELDING = 10;
165 private static final int YIELDED = 11; // unmounted but runnable
166
167 // monitor enter
168 private static final int BLOCKING = 12;
169 private static final int BLOCKED = 13; // unmounted
170 private static final int UNBLOCKED = 14; // unmounted but runnable
171
172 // monitor wait/timed-wait
173 private static final int WAITING = 15;
174 private static final int WAIT = 16; // waiting in Object.wait
175 private static final int TIMED_WAITING = 17;
176 private static final int TIMED_WAIT = 18; // waiting in timed-Object.wait
177
178 private static final int TERMINATED = 99; // final state
179
180 // parking permit made available by LockSupport.unpark
181 private volatile boolean parkPermit;
182
183 // blocking permit made available by unblocker thread when another thread exits monitor
184 private volatile boolean blockPermit;
185
186 // true when on the list of virtual threads waiting to be unblocked
187 private volatile boolean onWaitingList;
188
189 // next virtual thread on the list of virtual threads waiting to be unblocked
190 private volatile VirtualThread next;
191
192 // notified by Object.notify/notifyAll while waiting in Object.wait
193 private volatile boolean notified;
194
195 // true when waiting in Object.wait, false for VM internal uninterruptible Object.wait
196 private volatile boolean interruptibleWait;
197
198 // timed-wait support
199 private byte timedWaitSeqNo;
200
201 // timeout for timed-park and timed-wait, only accessed on current/carrier thread
202 private long timeout;
203
204 // timer task for timed-park and timed-wait, only accessed on current/carrier thread
205 private Future<?> timeoutTask;
206
207 // carrier thread when mounted, accessed by VM
208 private volatile Thread carrierThread;
209
210 // termination object when joining, created lazily if needed
211 private volatile CountDownLatch termination;
212
213 /**
214 * Return the built-in scheduler.
215 */
216 static VirtualThreadScheduler builtinScheduler() {
217 return BUILTIN_SCHEDULER;
218 }
219
220 /**
221 * Returns the default scheduler, usually the same as the built-in scheduler.
222 */
223 static VirtualThreadScheduler defaultScheduler() {
224 return DEFAULT_SCHEDULER;
225 }
226
227 /**
228 * Returns the continuation scope used for virtual threads.
229 */
230 static ContinuationScope continuationScope() {
231 return VTHREAD_SCOPE;
232 }
233
234 /**
235 * Return the scheduler for this thread.
236 * @param trusted true if caller is trusted, false if not trusted
237 */
238 VirtualThreadScheduler scheduler(boolean trusted) {
239 if (scheduler == BUILTIN_SCHEDULER && !trusted) {
240 return EXTERNAL_VIEW;
241 } else {
242 return scheduler;
243 }
244 }
245
246 /**
247 * Creates a new {@code VirtualThread} to run the given task with the given scheduler.
248 *
249 * @param scheduler the scheduler or null for default scheduler
250 * @param preferredCarrier the preferred carrier or null
251 * @param name thread name
252 * @param characteristics characteristics
253 * @param task the task to execute
254 */
255 VirtualThread(VirtualThreadScheduler scheduler,
256 Thread preferredCarrier,
257 String name,
258 int characteristics,
259 Runnable task,
260 Object att) {
261 super(name, characteristics, /*bound*/ false);
262 Objects.requireNonNull(task);
263
264 // use default scheduler if not provided
265 if (scheduler == null) {
266 scheduler = DEFAULT_SCHEDULER;
267 } else if (scheduler == EXTERNAL_VIEW) {
268 throw new UnsupportedOperationException();
269 }
270 this.scheduler = scheduler;
271 this.cont = new VThreadContinuation(this, task);
272
273 if (scheduler == BUILTIN_SCHEDULER) {
274 this.runContinuation = new BuiltinSchedulerTask(this);
275 } else {
276 this.runContinuation = new CustomSchedulerTask(this, preferredCarrier, att);
277 }
278 }
279
280 /**
281 * The task to execute when using the built-in scheduler.
282 */
283 static final class BuiltinSchedulerTask implements VirtualThreadTask {
284 private final VirtualThread vthread;
285 BuiltinSchedulerTask(VirtualThread vthread) {
286 this.vthread = vthread;
287 }
288 @Override
289 public Thread thread() {
290 return vthread;
291 }
292 @Override
293 public void run() {
294 vthread.runContinuation();;
295 }
296 @Override
297 public Thread preferredCarrier() {
298 throw new UnsupportedOperationException();
299 }
300 @Override
301 public Object attach(Object att) {
302 throw new UnsupportedOperationException();
303 }
304 @Override
305 public Object attachment() {
306 throw new UnsupportedOperationException();
307 }
308 }
309
310 /**
311 * The task to execute when using a custom scheduler.
312 */
313 static final class CustomSchedulerTask implements VirtualThreadTask {
314 private static final VarHandle ATT =
315 MhUtil.findVarHandle(MethodHandles.lookup(), "att", Object.class);
316 private final VirtualThread vthread;
317 private final Thread preferredCarrier;
318 private volatile Object att;
319 CustomSchedulerTask(VirtualThread vthread, Thread preferredCarrier, Object att) {
320 this.vthread = vthread;
321 this.preferredCarrier = preferredCarrier;
322 if (att != null) {
323 this.att = att;
324 }
325 }
326 @Override
327 public Thread thread() {
328 return vthread;
329 }
330 @Override
331 public void run() {
332 vthread.runContinuation();;
333 }
334 @Override
335 public Thread preferredCarrier() {
336 return preferredCarrier;
337 }
338 @Override
339 public Object attach(Object att) {
340 return ATT.getAndSet(this, att);
341 }
342 @Override
343 public Object attachment() {
344 return att;
345 }
346 }
347
348 /**
349 * The continuation that a virtual thread executes.
350 */
351 private static class VThreadContinuation extends Continuation {
352 VThreadContinuation(VirtualThread vthread, Runnable task) {
353 super(VTHREAD_SCOPE, wrap(vthread, task));
354 }
355 @Override
356 protected void onPinned(Continuation.Pinned reason) {
357 }
358 private static Runnable wrap(VirtualThread vthread, Runnable task) {
359 return new Runnable() {
360 @Hidden
361 @JvmtiHideEvents
362 public void run() {
363 vthread.endFirstTransition();
364 try {
365 vthread.run(task);
413 if (cont.isDone()) {
414 afterDone();
415 } else {
416 afterYield();
417 }
418 }
419 }
420
421 /**
422 * Cancel timeout task when continuing after timed-park or timed-wait.
423 * The timeout task may be executing, or may have already completed.
424 */
425 private void cancelTimeoutTask() {
426 if (timeoutTask != null) {
427 timeoutTask.cancel(false);
428 timeoutTask = null;
429 }
430 }
431
432 /**
433 * Submits the runContinuation task to the scheduler. For the built-in scheduler,
434 * the task will be pushed to the local queue if possible, otherwise it will be
435 * pushed to an external submission queue.
436 * @param retryOnOOME true to retry indefinitely if OutOfMemoryError is thrown
437 * @throws RejectedExecutionException
438 */
439 private void submitRunContinuation(boolean retryOnOOME) {
440 boolean done = false;
441 while (!done) {
442 try {
443 // Pin the continuation to prevent the virtual thread from unmounting
444 // when submitting a task. For the default scheduler this ensures that
445 // the carrier doesn't change when pushing a task. For other schedulers
446 // it avoids deadlock that could arise due to carriers and virtual
447 // threads contending for a lock.
448 if (currentThread().isVirtual()) {
449 Continuation.pin();
450 try {
451 scheduler.onContinue(runContinuation);
452 } finally {
453 Continuation.unpin();
454 }
455 } else {
456 scheduler.onContinue(runContinuation);
457 }
458 done = true;
459 } catch (RejectedExecutionException ree) {
460 submitFailed(ree);
461 throw ree;
462 } catch (OutOfMemoryError e) {
463 if (retryOnOOME) {
464 U.park(false, 100_000_000); // 100ms
465 } else {
466 throw e;
467 }
468 }
469 }
470 }
471
472 /**
473 * Submits the runContinuation task to the scheduler. For the default scheduler,
474 * and calling it on a worker thread, the task will be pushed to the local queue,
475 * otherwise it will be pushed to an external submission queue.
476 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
477 * @throws RejectedExecutionException
478 */
479 private void submitRunContinuation() {
480 submitRunContinuation(true);
481 }
482
483 /**
484 * Invoked from a carrier thread to lazy submit the runContinuation task to the
485 * carrier's local queue if the queue is empty. If not empty, or invoked by a thread
486 * for a custom scheduler, then it just submits the task to the scheduler.
487 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
488 * @throws RejectedExecutionException
489 * @see ForkJoinPool#lazySubmit(ForkJoinTask)
490 */
491 private void lazySubmitRunContinuation() {
492 assert !currentThread().isVirtual();
493 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
494 try {
495 ct.getPool().lazySubmit(ForkJoinTask.adapt(runContinuation));
496 } catch (RejectedExecutionException ree) {
497 submitFailed(ree);
498 throw ree;
499 } catch (OutOfMemoryError e) {
500 submitRunContinuation();
501 }
502 } else {
503 submitRunContinuation();
504 }
505 }
506
507 /**
508 * Invoked from a carrier thread to externally submit the runContinuation task to the
509 * scheduler. If invoked by a thread for a custom scheduler, then it just submits the
510 * task to the scheduler.
511 * If OutOfMemoryError is thrown then the submit will be retried until it succeeds.
512 * @throws RejectedExecutionException
513 * @see ForkJoinPool#externalSubmit(ForkJoinTask)
514 */
515 private void externalSubmitRunContinuation() {
516 assert !currentThread().isVirtual();
517 if (currentThread() instanceof CarrierThread ct) {
518 try {
519 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
520 } catch (RejectedExecutionException ree) {
521 submitFailed(ree);
522 throw ree;
523 } catch (OutOfMemoryError e) {
524 submitRunContinuation();
525 }
526 } else {
527 submitRunContinuation();
528 }
529 }
530
531 /**
532 * Invoked from Thread.start to externally submit the runContinuation task to the
533 * scheduler. If this virtual thread is scheduled by the built-in scheduler,
534 * and this method is called from a virtual thread scheduled by the built-in
535 * scheduler, then it uses externalSubmit to ensure that the task is pushed to an
536 * external submission queue rather than the local queue.
537 * @throws RejectedExecutionException
538 * @throws OutOfMemoryError
539 * @see ForkJoinPool#externalSubmit(ForkJoinTask)
540 */
541 private void externalSubmitRunContinuationOrThrow() {
542 try {
543 if (currentThread().isVirtual()) {
544 // Pin the continuation to prevent the virtual thread from unmounting
545 // when submitting a task. This avoids deadlock that could arise due to
546 // carriers and virtual threads contending for a lock.
547 Continuation.pin();
548 try {
549 if (scheduler == BUILTIN_SCHEDULER
550 && currentCarrierThread() instanceof CarrierThread ct) {
551 ct.getPool().externalSubmit(ForkJoinTask.adapt(runContinuation));
552 } else {
553 scheduler.onStart(runContinuation);
554 }
555 } finally {
556 Continuation.unpin();
557 }
558 } else {
559 scheduler.onStart(runContinuation);
560 }
561 } catch (RejectedExecutionException ree) {
562 submitFailed(ree);
563 throw ree;
564 }
565 }
566
567 /**
568 * If enabled, emits a JFR VirtualThreadSubmitFailedEvent.
569 */
570 private void submitFailed(RejectedExecutionException ree) {
571 var event = new VirtualThreadSubmitFailedEvent();
572 if (event.isEnabled()) {
573 event.javaThreadId = threadId();
574 event.exceptionMessage = ree.getMessage();
575 event.commit();
576 }
577 }
578
579 /**
580 * Runs a task in the context of this virtual thread.
581 */
582 private void run(Runnable task) {
583 assert Thread.currentThread() == this && state == RUNNING;
597 } finally {
598 // pop any remaining scopes from the stack, this may block
599 StackableScope.popAll();
600
601 // emit JFR event if enabled
602 if (VirtualThreadEndEvent.isTurnedOn()) {
603 var event = new VirtualThreadEndEvent();
604 event.javaThreadId = threadId();
605 event.commit();
606 }
607 }
608 }
609
610 /**
611 * Mounts this virtual thread onto the current platform thread. On
612 * return, the current thread is the virtual thread.
613 */
614 @ChangesCurrentThread
615 @ReservedStackAccess
616 private void mount() {
617 startTransition(/*mount*/true);
618 // We assume following volatile accesses provide equivalent
619 // of acquire ordering, otherwise we need U.loadFence() here.
620
621 // sets the carrier thread
622 Thread carrier = Thread.currentCarrierThread();
623 setCarrierThread(carrier);
624
625 // sync up carrier thread interrupted status if needed
626 if (interrupted) {
627 carrier.setInterrupt();
628 } else if (carrier.isInterrupted()) {
629 synchronized (interruptLock) {
630 // need to recheck interrupted status
631 if (!interrupted) {
632 carrier.clearInterrupt();
633 }
634 }
635 }
636
637 // set Thread.currentThread() to return this virtual thread
642 * Unmounts this virtual thread from the carrier. On return, the
643 * current thread is the current platform thread.
644 */
645 @ChangesCurrentThread
646 @ReservedStackAccess
647 private void unmount() {
648 assert !Thread.holdsLock(interruptLock);
649
650 // set Thread.currentThread() to return the platform thread
651 Thread carrier = this.carrierThread;
652 carrier.setCurrentThread(carrier);
653
654 // break connection to carrier thread, synchronized with interrupt
655 synchronized (interruptLock) {
656 setCarrierThread(null);
657 }
658 carrier.clearInterrupt();
659
660 // We assume previous volatile accesses provide equivalent
661 // of release ordering, otherwise we need U.storeFence() here.
662 endTransition(/*mount*/false);
663 }
664
665 /**
666 * Invokes Continuation.yield, notifying JVMTI (if enabled) to hide frames until
667 * the continuation continues.
668 */
669 @Hidden
670 private boolean yieldContinuation() {
671 startTransition(/*mount*/false);
672 try {
673 return Continuation.yield(VTHREAD_SCOPE);
674 } finally {
675 endTransition(/*mount*/true);
676 }
677 }
678
679 /**
680 * Invoked in the context of the carrier thread after the Continuation yields when
681 * parking, blocking on monitor enter, Object.wait, or Thread.yield.
682 */
683 private void afterYield() {
684 assert carrierThread == null;
685
686 // re-adjust parallelism if the virtual thread yielded when compensating
687 if (currentThread() instanceof CarrierThread ct) {
688 ct.endBlocking();
689 }
690
691 int s = state();
692
693 // LockSupport.park/parkNanos
694 if (s == PARKING || s == TIMED_PARKING) {
695 int newState;
700 long timeout = this.timeout;
701 assert timeout > 0;
702 timeoutTask = schedule(this::parkTimeoutExpired, timeout, NANOSECONDS);
703 setState(newState = TIMED_PARKED);
704 }
705
706 // may have been unparked while parking
707 if (parkPermit && compareAndSetState(newState, UNPARKED)) {
708 // lazy submit if local queue is empty
709 lazySubmitRunContinuation();
710 }
711 return;
712 }
713
714 // Thread.yield
715 if (s == YIELDING) {
716 setState(YIELDED);
717
718 // external submit if there are no tasks in the local task queue
719 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
720 externalSubmitRunContinuation();
721 } else {
722 submitRunContinuation();
723 }
724 return;
725 }
726
727 // blocking on monitorenter
728 if (s == BLOCKING) {
729 setState(BLOCKED);
730
731 // may have been unblocked while blocking
732 if (blockPermit && compareAndSetState(BLOCKED, UNBLOCKED)) {
733 // lazy submit if local queue is empty
734 lazySubmitRunContinuation();
735 }
736 return;
737 }
738
739 // Object.wait
740 if (s == WAITING || s == TIMED_WAITING) {
857 @Override
858 public void run() {
859 // do nothing
860 }
861
862 /**
863 * Parks until unparked or interrupted. If already unparked then the parking
864 * permit is consumed and this method completes immediately (meaning it doesn't
865 * yield). It also completes immediately if the interrupted status is set.
866 */
867 @Override
868 void park() {
869 assert Thread.currentThread() == this;
870
871 // complete immediately if parking permit available or interrupted
872 if (getAndSetParkPermit(false) || interrupted)
873 return;
874
875 // park the thread
876 boolean yielded = false;
877 long eventStartTime = VirtualThreadParkEvent.eventStartTime();
878 setState(PARKING);
879 try {
880 yielded = yieldContinuation();
881 } catch (OutOfMemoryError e) {
882 // park on carrier
883 } finally {
884 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
885 if (yielded) {
886 VirtualThreadParkEvent.offer(eventStartTime, Long.MIN_VALUE);
887 } else {
888 assert state() == PARKING;
889 setState(RUNNING);
890 }
891 }
892
893 // park on the carrier thread when pinned
894 if (!yielded) {
895 parkOnCarrierThread(false, 0);
896 }
897 }
898
899 /**
900 * Parks up to the given waiting time or until unparked or interrupted.
901 * If already unparked then the parking permit is consumed and this method
902 * completes immediately (meaning it doesn't yield). It also completes immediately
903 * if the interrupted status is set or the waiting time is {@code <= 0}.
904 *
905 * @param nanos the maximum number of nanoseconds to wait.
906 */
907 @Override
908 void parkNanos(long nanos) {
909 assert Thread.currentThread() == this;
910
911 // complete immediately if parking permit available or interrupted
912 if (getAndSetParkPermit(false) || interrupted)
913 return;
914
915 // park the thread for the waiting time
916 if (nanos > 0) {
917 long startTime = System.nanoTime();
918
919 // park the thread, afterYield will schedule the thread to unpark
920 boolean yielded = false;
921 long eventStartTime = VirtualThreadParkEvent.eventStartTime();
922 timeout = nanos;
923 setState(TIMED_PARKING);
924 try {
925 yielded = yieldContinuation();
926 } catch (OutOfMemoryError e) {
927 // park on carrier
928 } finally {
929 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
930 if (yielded) {
931 VirtualThreadParkEvent.offer(eventStartTime, nanos);
932 } else {
933 assert state() == TIMED_PARKING;
934 setState(RUNNING);
935 }
936 }
937
938 // park on carrier thread for remaining time when pinned (or OOME)
939 if (!yielded) {
940 long remainingNanos = nanos - (System.nanoTime() - startTime);
941 parkOnCarrierThread(true, remainingNanos);
942 }
943 }
944 }
945
946 /**
947 * Parks the current carrier thread up to the given waiting time or until
948 * unparked or interrupted. If the virtual thread is interrupted then the
949 * interrupted status will be propagated to the carrier thread.
950 * @param timed true for a timed park, false for untimed
951 * @param nanos the waiting time in nanoseconds
952 */
1016 }
1017 }
1018 }
1019
1020 /**
1021 * Invoked by unblocker thread to unblock this virtual thread.
1022 */
1023 private void unblock() {
1024 assert !Thread.currentThread().isVirtual();
1025 blockPermit = true;
1026 if (state() == BLOCKED && compareAndSetState(BLOCKED, UNBLOCKED)) {
1027 submitRunContinuation();
1028 }
1029 }
1030
1031 /**
1032 * Invoked by FJP worker thread or STPE thread when park timeout expires.
1033 */
1034 private void parkTimeoutExpired() {
1035 assert !VirtualThread.currentThread().isVirtual();
1036 if (!getAndSetParkPermit(true)) {
1037 int s = state();
1038 if ((s == PARKED || s == TIMED_PARKED) && compareAndSetState(s, UNPARKED)) {
1039 lazySubmitRunContinuation();
1040 }
1041 }
1042 }
1043
1044 /**
1045 * Invoked by FJP worker thread or STPE thread when wait timeout expires.
1046 * If the virtual thread is in timed-wait then this method will unblock the thread
1047 * and submit its task so that it continues and attempts to reenter the monitor.
1048 * This method does nothing if the thread has been woken by notify or interrupt.
1049 */
1050 private void waitTimeoutExpired(byte seqNo) {
1051 assert !Thread.currentThread().isVirtual();
1052
1053 synchronized (timedWaitLock()) {
1054 if (seqNo != timedWaitSeqNo) {
1055 // this timeout task is for a past timed-wait
1056 return;
1057 }
1058 if (!compareAndSetState(TIMED_WAIT, UNBLOCKED)) {
1059 // already unblocked
1060 return;
1061 }
1062 }
1063
1064 lazySubmitRunContinuation();
1065 }
1066
1067 /**
1068 * Attempts to yield the current virtual thread (Thread.yield).
1069 */
1070 void tryYield() {
1071 assert Thread.currentThread() == this;
1072 setState(YIELDING);
1073 boolean yielded = false;
1074 try {
1075 yielded = yieldContinuation(); // may throw
1076 } finally {
1077 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
1078 if (!yielded) {
1079 assert state() == YIELDING;
1080 setState(RUNNING);
1081 }
1082 }
1083 }
1084
1212 @Override
1213 boolean getAndClearInterrupt() {
1214 assert Thread.currentThread() == this;
1215 boolean oldValue = interrupted;
1216 if (oldValue) {
1217 disableSuspendAndPreempt();
1218 try {
1219 synchronized (interruptLock) {
1220 interrupted = false;
1221 carrierThread.clearInterrupt();
1222 }
1223 } finally {
1224 enableSuspendAndPreempt();
1225 }
1226 }
1227 return oldValue;
1228 }
1229
1230 @Override
1231 Thread.State threadState() {
1232 switch (state()) {
1233 case NEW:
1234 return Thread.State.NEW;
1235 case STARTED:
1236 // return NEW if thread container not yet set
1237 if (threadContainer() == null) {
1238 return Thread.State.NEW;
1239 } else {
1240 return Thread.State.RUNNABLE;
1241 }
1242 case UNPARKED:
1243 case UNBLOCKED:
1244 case YIELDED:
1245 // runnable, not mounted
1246 return Thread.State.RUNNABLE;
1247 case RUNNING:
1248 // if mounted then return state of carrier thread
1249 if (Thread.currentThread() != this) {
1250 disableSuspendAndPreempt();
1251 try {
1252 synchronized (carrierThreadAccessLock()) {
1280 case BLOCKED:
1281 return Thread.State.BLOCKED;
1282 case TERMINATED:
1283 return Thread.State.TERMINATED;
1284 default:
1285 throw new InternalError();
1286 }
1287 }
1288
1289 @Override
1290 boolean alive() {
1291 int s = state;
1292 return (s != NEW && s != TERMINATED);
1293 }
1294
1295 @Override
1296 boolean isTerminated() {
1297 return (state == TERMINATED);
1298 }
1299
1300 @Override
1301 public String toString() {
1302 StringBuilder sb = new StringBuilder("VirtualThread[#");
1303 sb.append(threadId());
1304 String name = getName();
1305 if (!name.isEmpty()) {
1306 sb.append(",");
1307 sb.append(name);
1308 }
1309 sb.append("]/");
1310
1311 // add the carrier state and thread name when mounted
1312 boolean mounted;
1313 if (Thread.currentThread() == this) {
1314 mounted = appendCarrierInfo(sb);
1315 } else {
1316 disableSuspendAndPreempt();
1317 try {
1318 synchronized (carrierThreadAccessLock()) {
1319 mounted = appendCarrierInfo(sb);
1450 // resuming the virtual thread's continuation on the carrier.
1451 // An "unmount transition" embodies the steps to transfer control from a virtual
1452 // thread to its carrier, suspending the virtual thread's continuation, and
1453 // restoring the thread identity to the platform thread.
1454 // The notifications to the VM are necessary in order to coordinate with functions
1455 // (JVMTI mostly) that disable transitions for one or all virtual threads. Starting
1456 // a transition may block if transitions are disabled. Ending a transition may
1457 // notify a thread that is waiting to disable transitions. The notifications are
1458 // also used to post JVMTI events for virtual thread start and end.
1459
1460 @IntrinsicCandidate
1461 @JvmtiMountTransition
1462 private native void endFirstTransition();
1463
1464 @IntrinsicCandidate
1465 @JvmtiMountTransition
1466 private native void startFinalTransition();
1467
1468 @IntrinsicCandidate
1469 @JvmtiMountTransition
1470 private native void startTransition(boolean mount);
1471
1472 @IntrinsicCandidate
1473 @JvmtiMountTransition
1474 private native void endTransition(boolean mount);
1475
1476 @IntrinsicCandidate
1477 private static native void notifyJvmtiDisableSuspend(boolean enter);
1478
1479 private static native void registerNatives();
1480 static {
1481 registerNatives();
1482
1483 // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1484 var group = Thread.virtualThreadGroup();
1485
1486 // ensure event class is initialized
1487 try {
1488 MethodHandles.lookup().ensureInitialized(VirtualThreadParkEvent.class);
1489 } catch (IllegalAccessException e) {
1490 throw new ExceptionInInitializerError(e);
1491 }
1492 }
1493
1494 /**
1495 * Loads a VirtualThreadScheduler with the given class name. The class must be public
1496 * in an exported package, with public one-arg or no-arg constructor, and be visible
1497 * to the system class loader.
1498 * @param delegate the scheduler that the custom scheduler may delegate to
1499 * @param cn the class name of the custom scheduler
1500 */
1501 private static VirtualThreadScheduler loadCustomScheduler(VirtualThreadScheduler delegate, String cn) {
1502 VirtualThreadScheduler scheduler;
1503 try {
1504 Class<?> clazz = Class.forName(cn, true, ClassLoader.getSystemClassLoader());
1505 // 1-arg constructor
1506 try {
1507 Constructor<?> ctor = clazz.getConstructor(VirtualThreadScheduler.class);
1508 return (VirtualThreadScheduler) ctor.newInstance(delegate);
1509 } catch (NoSuchMethodException e) {
1510 // 0-arg constructor
1511 Constructor<?> ctor = clazz.getConstructor();
1512 scheduler = (VirtualThreadScheduler) ctor.newInstance();
1513 }
1514 } catch (Exception ex) {
1515 throw new Error(ex);
1516 }
1517 System.err.println("WARNING: Using custom default scheduler, this is an experimental feature!");
1518 return scheduler;
1519 }
1520
1521 /**
1522 * Creates the built-in ForkJoinPool scheduler.
1523 * @param wrapped true if wrapped by a custom default scheduler
1524 */
1525 private static BuiltinScheduler createBuiltinScheduler(boolean wrapped) {
1526 int parallelism, maxPoolSize, minRunnable;
1527 String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1528 String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1529 String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1530 if (parallelismValue != null) {
1531 parallelism = Integer.parseInt(parallelismValue);
1532 } else {
1533 parallelism = Runtime.getRuntime().availableProcessors();
1534 }
1535 if (maxPoolSizeValue != null) {
1536 maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1537 parallelism = Integer.min(parallelism, maxPoolSize);
1538 } else {
1539 maxPoolSize = Integer.max(parallelism, 256);
1540 }
1541 if (minRunnableValue != null) {
1542 minRunnable = Integer.parseInt(minRunnableValue);
1543 } else {
1544 minRunnable = Integer.max(parallelism / 2, 1);
1545 }
1546 return new BuiltinScheduler(parallelism, maxPoolSize, minRunnable, wrapped);
1547 }
1548
1549 /**
1550 * The built-in ForkJoinPool scheduler.
1551 */
1552 private static class BuiltinScheduler
1553 extends ForkJoinPool implements VirtualThreadScheduler {
1554
1555 BuiltinScheduler(int parallelism, int maxPoolSize, int minRunnable, boolean wrapped) {
1556 ForkJoinWorkerThreadFactory factory = wrapped
1557 ? ForkJoinPool.defaultForkJoinWorkerThreadFactory
1558 : CarrierThread::new;
1559 Thread.UncaughtExceptionHandler handler = (t, e) -> { };
1560 boolean asyncMode = true; // FIFO
1561 super(parallelism, factory, handler, asyncMode,
1562 0, maxPoolSize, minRunnable, pool -> true, 30, SECONDS);
1563 }
1564
1565 private void adaptAndExecute(Runnable task) {
1566 execute(ForkJoinTask.adapt(task));
1567 }
1568
1569 @Override
1570 public void onStart(VirtualThreadTask task) {
1571 adaptAndExecute(task);
1572 }
1573
1574 @Override
1575 public void onContinue(VirtualThreadTask task) {
1576 adaptAndExecute(task);
1577 }
1578
1579 /**
1580 * Wraps the scheduler to avoid leaking a direct reference with
1581 * {@link VirtualThreadScheduler#current()}.
1582 */
1583 VirtualThreadScheduler createExternalView() {
1584 BuiltinScheduler builtin = this;
1585 return new VirtualThreadScheduler() {
1586 private void execute(VirtualThreadTask task) {
1587 var vthread = (VirtualThread) task.thread();
1588 VirtualThreadScheduler scheduler = vthread.scheduler;
1589 if (scheduler == this || scheduler == DEFAULT_SCHEDULER) {
1590 builtin.adaptAndExecute(task);
1591 } else {
1592 throw new IllegalArgumentException();
1593 }
1594 }
1595 @Override
1596 public void onStart(VirtualThreadTask task) {
1597 execute(task);
1598 }
1599 @Override
1600 public void onContinue(VirtualThreadTask task) {
1601 execute(task);
1602 }
1603 @Override
1604 public String toString() {
1605 return builtin.toString();
1606 }
1607 };
1608 }
1609 }
1610
1611 /**
1612 * Schedule a runnable task to run after a delay.
1613 */
1614 private Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1615 if (scheduler == BUILTIN_SCHEDULER) {
1616 return BUILTIN_SCHEDULER.schedule(command, delay, unit);
1617 } else {
1618 return DelayedTaskSchedulers.schedule(command, delay, unit);
1619 }
1620 }
1621
1622 /**
1623 * Supports scheduling a runnable task to run after a delay. It uses a number
1624 * of ScheduledThreadPoolExecutor instances to reduce contention on the delayed
1625 * work queue used. This class is used when using a custom scheduler.
1626 */
1627 private static class DelayedTaskSchedulers {
1628 private static final ScheduledExecutorService[] INSTANCE = createDelayedTaskSchedulers();
1629
1630 static Future<?> schedule(Runnable command, long delay, TimeUnit unit) {
1631 long tid = Thread.currentThread().threadId();
1632 int index = (int) tid & (INSTANCE.length - 1);
1633 return INSTANCE[index].schedule(command, delay, unit);
1634 }
1635
1636 private static ScheduledExecutorService[] createDelayedTaskSchedulers() {
|