7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package java.lang;
26
27 import java.security.AccessController;
28 import java.security.PrivilegedAction;
29 import java.util.Locale;
30 import java.util.Objects;
31 import java.util.concurrent.Callable;
32 import java.util.concurrent.CountDownLatch;
33 import java.util.concurrent.Executor;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ForkJoinPool;
36 import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;
37 import java.util.concurrent.ForkJoinTask;
38 import java.util.concurrent.ForkJoinWorkerThread;
39 import java.util.concurrent.Future;
40 import java.util.concurrent.RejectedExecutionException;
41 import java.util.concurrent.ScheduledExecutorService;
42 import java.util.concurrent.ScheduledThreadPoolExecutor;
43 import java.util.concurrent.TimeUnit;
44 import jdk.internal.event.VirtualThreadEndEvent;
45 import jdk.internal.event.VirtualThreadPinnedEvent;
46 import jdk.internal.event.VirtualThreadStartEvent;
47 import jdk.internal.event.VirtualThreadSubmitFailedEvent;
48 import jdk.internal.misc.CarrierThread;
49 import jdk.internal.misc.InnocuousThread;
50 import jdk.internal.misc.Unsafe;
51 import jdk.internal.vm.Continuation;
52 import jdk.internal.vm.ContinuationScope;
53 import jdk.internal.vm.StackableScope;
54 import jdk.internal.vm.ThreadContainer;
55 import jdk.internal.vm.ThreadContainers;
56 import jdk.internal.vm.annotation.ChangesCurrentThread;
57 import jdk.internal.vm.annotation.Hidden;
58 import jdk.internal.vm.annotation.IntrinsicCandidate;
59 import jdk.internal.vm.annotation.JvmtiMountTransition;
60 import jdk.internal.vm.annotation.ReservedStackAccess;
61 import sun.nio.ch.Interruptible;
62 import sun.security.action.GetPropertyAction;
63 import static java.util.concurrent.TimeUnit.*;
64
65 /**
66 * A thread that is scheduled by the Java virtual machine rather than the operating system.
67 */
68 final class VirtualThread extends BaseVirtualThread {
69 private static final Unsafe U = Unsafe.getUnsafe();
70 private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
71 private static final ForkJoinPool DEFAULT_SCHEDULER = createDefaultScheduler();
72 private static final ScheduledExecutorService[] DELAYED_TASK_SCHEDULERS = createDelayedTaskSchedulers();
73 private static final int TRACE_PINNING_MODE = tracePinningMode();
74
75 private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
76 private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
77 private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
78 private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
79
80 // scheduler and continuation
81 private final Executor scheduler;
82 private final Continuation cont;
83 private final Runnable runContinuation;
84
85 // virtual thread state, accessed by VM
86 private volatile int state;
87
88 /*
89 * Virtual thread state transitions:
90 *
91 * NEW -> STARTED // Thread.start, schedule to run
92 * STARTED -> TERMINATED // failed to start
93 * STARTED -> RUNNING // first run
94 * RUNNING -> TERMINATED // done
95 *
96 * RUNNING -> PARKING // Thread parking with LockSupport.park
97 * PARKING -> PARKED // cont.yield successful, parked indefinitely
98 * PARKING -> PINNED // cont.yield failed, parked indefinitely on carrier
99 * PARKED -> UNPARKED // unparked, may be scheduled to continue
100 * PINNED -> RUNNING // unparked, continue execution on same carrier
101 * UNPARKED -> RUNNING // continue execution after park
102 *
103 * RUNNING -> TIMED_PARKING // Thread parking with LockSupport.parkNanos
104 * TIMED_PARKING -> TIMED_PARKED // cont.yield successful, timed-parked
105 * TIMED_PARKING -> TIMED_PINNED // cont.yield failed, timed-parked on carrier
106 * TIMED_PARKED -> UNPARKED // unparked, may be scheduled to continue
107 * TIMED_PINNED -> RUNNING // unparked, continue execution on same carrier
108 *
109 * RUNNING -> YIELDING // Thread.yield
110 * YIELDING -> YIELDED // cont.yield successful, may be scheduled to continue
111 * YIELDING -> RUNNING // cont.yield failed
112 * YIELDED -> RUNNING // continue execution after Thread.yield
113 */
114 private static final int NEW = 0;
115 private static final int STARTED = 1;
116 private static final int RUNNING = 2; // runnable-mounted
117
118 // untimed and timed parking
119 private static final int PARKING = 3;
120 private static final int PARKED = 4; // unmounted
121 private static final int PINNED = 5; // mounted
122 private static final int TIMED_PARKING = 6;
123 private static final int TIMED_PARKED = 7; // unmounted
124 private static final int TIMED_PINNED = 8; // mounted
125 private static final int UNPARKED = 9; // unmounted but runnable
126
127 // Thread.yield
128 private static final int YIELDING = 10;
129 private static final int YIELDED = 11; // unmounted but runnable
130
131 private static final int TERMINATED = 99; // final state
132
133 // can be suspended from scheduling when unmounted
134 private static final int SUSPENDED = 1 << 8;
135
136 // parking permit
137 private volatile boolean parkPermit;
138
139 // carrier thread when mounted, accessed by VM
140 private volatile Thread carrierThread;
141
142 // termination object when joining, created lazily if needed
143 private volatile CountDownLatch termination;
144
145 /**
146 * Returns the continuation scope used for virtual threads.
147 */
148 static ContinuationScope continuationScope() {
149 return VTHREAD_SCOPE;
150 }
151
152 /**
153 * Creates a new {@code VirtualThread} to run the given task with the given
154 * scheduler. If the given scheduler is {@code null} and the current thread
155 * is a platform thread then the newly created virtual thread will use the
156 * default scheduler. If given scheduler is {@code null} and the current
157 * thread is a virtual thread then the current thread's scheduler is used.
158 *
159 * @param scheduler the scheduler or null
160 * @param name thread name
161 * @param characteristics characteristics
162 * @param task the task to execute
163 */
164 VirtualThread(Executor scheduler, String name, int characteristics, Runnable task) {
172 scheduler = vparent.scheduler;
173 } else {
174 scheduler = DEFAULT_SCHEDULER;
175 }
176 }
177
178 this.scheduler = scheduler;
179 this.cont = new VThreadContinuation(this, task);
180 this.runContinuation = this::runContinuation;
181 }
182
183 /**
184 * The continuation that a virtual thread executes.
185 */
186 private static class VThreadContinuation extends Continuation {
187 VThreadContinuation(VirtualThread vthread, Runnable task) {
188 super(VTHREAD_SCOPE, wrap(vthread, task));
189 }
190 @Override
191 protected void onPinned(Continuation.Pinned reason) {
192 if (TRACE_PINNING_MODE > 0) {
193 boolean printAll = (TRACE_PINNING_MODE == 1);
194 VirtualThread vthread = (VirtualThread) Thread.currentThread();
195 int oldState = vthread.state();
196 try {
197 // avoid printing when in transition states
198 vthread.setState(RUNNING);
199 PinnedThreadPrinter.printStackTrace(System.out, reason, printAll);
200 } finally {
201 vthread.setState(oldState);
202 }
203 }
204 }
205 private static Runnable wrap(VirtualThread vthread, Runnable task) {
206 return new Runnable() {
207 @Hidden
208 public void run() {
209 vthread.run(task);
210 }
211 };
212 }
213 }
214
215 /**
216 * Runs or continues execution on the current thread. The virtual thread is mounted
217 * on the current thread before the task runs or continues. It unmounts when the
218 * task completes or yields.
219 */
220 @ChangesCurrentThread // allow mount/unmount to be inlined
221 private void runContinuation() {
222 // the carrier must be a platform thread
223 if (Thread.currentThread().isVirtual()) {
224 throw new WrongThreadException();
225 }
226
227 // set state to RUNNING
228 int initialState = state();
229 if (initialState == STARTED || initialState == UNPARKED || initialState == YIELDED) {
230 // newly started or continue after parking/blocking/Thread.yield
231 if (!compareAndSetState(initialState, RUNNING)) {
232 return;
233 }
234 // consume parking permit when continuing after parking
235 if (initialState == UNPARKED) {
236 setParkPermit(false);
237 }
238 } else {
239 // not runnable
240 return;
241 }
242
243 mount();
244 try {
245 cont.run();
246 } finally {
247 unmount();
248 if (cont.isDone()) {
249 afterDone();
462 synchronized (interruptLock) {
463 setCarrierThread(null);
464 }
465 carrier.clearInterrupt();
466
467 // notify JVMTI after unmount
468 notifyJvmtiUnmount(/*hide*/false);
469 }
470
471 /**
472 * Sets the current thread to the current carrier thread.
473 */
474 @ChangesCurrentThread
475 @JvmtiMountTransition
476 private void switchToCarrierThread() {
477 notifyJvmtiHideFrames(true);
478 Thread carrier = this.carrierThread;
479 assert Thread.currentThread() == this
480 && carrier == Thread.currentCarrierThread();
481 carrier.setCurrentThread(carrier);
482 }
483
484 /**
485 * Sets the current thread to the given virtual thread.
486 */
487 @ChangesCurrentThread
488 @JvmtiMountTransition
489 private static void switchToVirtualThread(VirtualThread vthread) {
490 Thread carrier = vthread.carrierThread;
491 assert carrier == Thread.currentCarrierThread();
492 carrier.setCurrentThread(vthread);
493 notifyJvmtiHideFrames(false);
494 }
495
496 /**
497 * Executes the given value returning task on the current carrier thread.
498 */
499 @ChangesCurrentThread
500 <V> V executeOnCarrierThread(Callable<V> task) throws Exception {
501 assert Thread.currentThread() == this;
549 } else {
550 submitRunContinuation();
551 }
552 }
553 return;
554 }
555
556 // Thread.yield
557 if (s == YIELDING) {
558 setState(YIELDED);
559
560 // external submit if there are no tasks in the local task queue
561 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
562 externalSubmitRunContinuation(ct.getPool());
563 } else {
564 submitRunContinuation();
565 }
566 return;
567 }
568
569 assert false;
570 }
571
572 /**
573 * Invoked after the continuation completes.
574 */
575 private void afterDone() {
576 afterDone(true);
577 }
578
579 /**
580 * Invoked after the continuation completes (or start failed). Sets the thread
581 * state to TERMINATED and notifies anyone waiting for the thread to terminate.
582 *
583 * @param notifyContainer true if its container should be notified
584 */
585 private void afterDone(boolean notifyContainer) {
586 assert carrierThread == null;
587 setState(TERMINATED);
588
716 }
717
718 // park on carrier thread for remaining time when pinned
719 if (!yielded) {
720 long remainingNanos = nanos - (System.nanoTime() - startTime);
721 parkOnCarrierThread(true, remainingNanos);
722 }
723 }
724 }
725
726 /**
727 * Parks the current carrier thread up to the given waiting time or until
728 * unparked or interrupted. If the virtual thread is interrupted then the
729 * interrupt status will be propagated to the carrier thread.
730 * @param timed true for a timed park, false for untimed
731 * @param nanos the waiting time in nanoseconds
732 */
733 private void parkOnCarrierThread(boolean timed, long nanos) {
734 assert state() == RUNNING;
735
736 VirtualThreadPinnedEvent event;
737 try {
738 event = new VirtualThreadPinnedEvent();
739 event.begin();
740 } catch (OutOfMemoryError e) {
741 event = null;
742 }
743
744 setState(timed ? TIMED_PINNED : PINNED);
745 try {
746 if (!parkPermit) {
747 if (!timed) {
748 U.park(false, 0);
749 } else if (nanos > 0) {
750 U.park(false, nanos);
751 }
752 }
753 } finally {
754 setState(RUNNING);
755 }
756
757 // consume parking permit
758 setParkPermit(false);
759
760 if (event != null) {
761 try {
762 event.commit();
763 } catch (OutOfMemoryError e) {
764 // ignore
765 }
766 }
767 }
768
769 /**
770 * Schedule this virtual thread to be unparked after a given delay.
771 */
772 @ChangesCurrentThread
773 private Future<?> scheduleUnpark(long nanos) {
774 assert Thread.currentThread() == this;
775 // need to switch to current carrier thread to avoid nested parking
776 switchToCarrierThread();
777 try {
778 return schedule(this::unpark, nanos, NANOSECONDS);
779 } finally {
780 switchToVirtualThread(this);
781 }
782 }
783
784 /**
785 * Cancels a task if it has not completed.
786 */
787 @ChangesCurrentThread
788 private void cancel(Future<?> future) {
789 assert Thread.currentThread() == this;
790 if (!future.isDone()) {
791 // need to switch to current carrier thread to avoid nested parking
792 switchToCarrierThread();
793 try {
794 future.cancel(false);
795 } finally {
796 switchToVirtualThread(this);
797 }
798 }
799 }
800
801 /**
802 * Re-enables this virtual thread for scheduling. If this virtual thread is parked
803 * then its task is scheduled to continue, otherwise its next call to {@code park} or
804 * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block.
805 * @throws RejectedExecutionException if the scheduler cannot accept a task
817
818 // unparked while parked when pinned
819 if (s == PINNED || s == TIMED_PINNED) {
820 // unpark carrier thread when pinned
821 disableSuspendAndPreempt();
822 try {
823 synchronized (carrierThreadAccessLock()) {
824 Thread carrier = carrierThread;
825 if (carrier != null && ((s = state()) == PINNED || s == TIMED_PINNED)) {
826 U.unpark(carrier);
827 }
828 }
829 } finally {
830 enableSuspendAndPreempt();
831 }
832 return;
833 }
834 }
835 }
836
837 /**
838 * Attempts to yield the current virtual thread (Thread.yield).
839 */
840 void tryYield() {
841 assert Thread.currentThread() == this;
842 setState(YIELDING);
843 boolean yielded = false;
844 try {
845 yielded = yieldContinuation(); // may throw
846 } finally {
847 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
848 if (!yielded) {
849 assert state() == YIELDING;
850 setState(RUNNING);
851 }
852 }
853 }
854
855 /**
856 * Sleep the current thread for the given sleep time (in nanoseconds). If
947 if (blocker != null) {
948 blocker.interrupt(this);
949 }
950
951 // interrupt carrier thread if mounted
952 Thread carrier = carrierThread;
953 if (carrier != null) carrier.setInterrupt();
954 }
955 } finally {
956 enableSuspendAndPreempt();
957 }
958
959 // notify blocker after releasing interruptLock
960 if (blocker != null) {
961 blocker.postInterrupt();
962 }
963
964 // make available parking permit, unpark thread if parked
965 unpark();
966
967 } else {
968 interrupted = true;
969 carrierThread.setInterrupt();
970 setParkPermit(true);
971 }
972 }
973
974 @Override
975 public boolean isInterrupted() {
976 return interrupted;
977 }
978
979 @Override
980 boolean getAndClearInterrupt() {
981 assert Thread.currentThread() == this;
982 boolean oldValue = interrupted;
983 if (oldValue) {
984 disableSuspendAndPreempt();
985 try {
986 synchronized (interruptLock) {
994 return oldValue;
995 }
996
997 @Override
998 Thread.State threadState() {
999 int s = state();
1000 switch (s & ~SUSPENDED) {
1001 case NEW:
1002 return Thread.State.NEW;
1003 case STARTED:
1004 // return NEW if thread container not yet set
1005 if (threadContainer() == null) {
1006 return Thread.State.NEW;
1007 } else {
1008 return Thread.State.RUNNABLE;
1009 }
1010 case UNPARKED:
1011 case YIELDED:
1012 // runnable, not mounted
1013 return Thread.State.RUNNABLE;
1014 case RUNNING:
1015 // if mounted then return state of carrier thread
1016 if (Thread.currentThread() != this) {
1017 disableSuspendAndPreempt();
1018 try {
1019 synchronized (carrierThreadAccessLock()) {
1020 Thread carrierThread = this.carrierThread;
1021 if (carrierThread != null) {
1022 return carrierThread.threadState();
1023 }
1024 }
1025 } finally {
1026 enableSuspendAndPreempt();
1027 }
1028 }
1029 // runnable, mounted
1030 return Thread.State.RUNNABLE;
1031 case PARKING:
1032 case TIMED_PARKING:
1033 case YIELDING:
1034 // runnable, in transition
1035 return Thread.State.RUNNABLE;
1036 case PARKED:
1037 case PINNED:
1038 return State.WAITING;
1039 case TIMED_PARKED:
1040 case TIMED_PINNED:
1041 return State.TIMED_WAITING;
1042 case TERMINATED:
1043 return Thread.State.TERMINATED;
1044 default:
1045 throw new InternalError();
1046 }
1047 }
1048
1049 @Override
1050 boolean alive() {
1051 int s = state;
1052 return (s != NEW && s != TERMINATED);
1053 }
1054
1055 @Override
1056 boolean isTerminated() {
1057 return (state == TERMINATED);
1058 }
1059
1060 @Override
1061 StackTraceElement[] asyncGetStackTrace() {
1062 StackTraceElement[] stackTrace;
1063 do {
1064 stackTrace = (carrierThread != null)
1065 ? super.asyncGetStackTrace() // mounted
1066 : tryGetStackTrace(); // unmounted
1067 if (stackTrace == null) {
1068 Thread.yield();
1069 }
1070 } while (stackTrace == null);
1071 return stackTrace;
1072 }
1073
1074 /**
1075 * Returns the stack trace for this virtual thread if it is unmounted.
1076 * Returns null if the thread is mounted or in transition.
1077 */
1078 private StackTraceElement[] tryGetStackTrace() {
1079 int initialState = state() & ~SUSPENDED;
1080 switch (initialState) {
1081 case NEW, STARTED, TERMINATED -> {
1082 return new StackTraceElement[0]; // unmounted, empty stack
1083 }
1084 case RUNNING, PINNED, TIMED_PINNED -> {
1085 return null; // mounted
1086 }
1087 case PARKED, TIMED_PARKED -> {
1088 // unmounted, not runnable
1089 }
1090 case UNPARKED, YIELDED -> {
1091 // unmounted, runnable
1092 }
1093 case PARKING, TIMED_PARKING, YIELDING -> {
1094 return null; // in transition
1095 }
1096 default -> throw new InternalError("" + initialState);
1097 }
1098
1099 // thread is unmounted, prevent it from continuing
1100 int suspendedState = initialState | SUSPENDED;
1101 if (!compareAndSetState(initialState, suspendedState)) {
1102 return null;
1103 }
1104
1105 // get stack trace and restore state
1106 StackTraceElement[] stack;
1107 try {
1108 stack = cont.getStackTrace();
1109 } finally {
1110 assert state == suspendedState;
1111 setState(initialState);
1112 }
1113 boolean resubmit = switch (initialState) {
1114 case UNPARKED, YIELDED -> {
1115 // resubmit as task may have run while suspended
1116 yield true;
1117 }
1118 case PARKED, TIMED_PARKED -> {
1119 // resubmit if unparked while suspended
1120 yield parkPermit && compareAndSetState(initialState, UNPARKED);
1121 }
1122 default -> throw new InternalError();
1123 };
1124 if (resubmit) {
1125 submitRunContinuation();
1126 }
1127 return stack;
1128 }
1129
1130 @Override
1131 public String toString() {
1132 StringBuilder sb = new StringBuilder("VirtualThread[#");
1133 sb.append(threadId());
1134 String name = getName();
1135 if (!name.isEmpty()) {
1136 sb.append(",");
1137 sb.append(name);
1138 }
1139 sb.append("]/");
1140
1141 // add the carrier state and thread name when mounted
1196 private CountDownLatch getTermination() {
1197 CountDownLatch termination = this.termination;
1198 if (termination == null) {
1199 termination = new CountDownLatch(1);
1200 if (!U.compareAndSetReference(this, TERMINATION, null, termination)) {
1201 termination = this.termination;
1202 }
1203 }
1204 return termination;
1205 }
1206
1207 /**
1208 * Returns the lock object to synchronize on when accessing carrierThread.
1209 * The lock prevents carrierThread from being reset to null during unmount.
1210 */
1211 private Object carrierThreadAccessLock() {
1212 // return interruptLock as unmount has to coordinate with interrupt
1213 return interruptLock;
1214 }
1215
1216 /**
1217 * Disallow the current thread be suspended or preempted.
1218 */
1219 private void disableSuspendAndPreempt() {
1220 notifyJvmtiDisableSuspend(true);
1221 Continuation.pin();
1222 }
1223
1224 /**
1225 * Allow the current thread be suspended or preempted.
1226 */
1227 private void enableSuspendAndPreempt() {
1228 Continuation.unpin();
1229 notifyJvmtiDisableSuspend(false);
1230 }
1231
1232 // -- wrappers for get/set of state, parking permit, and carrier thread --
1233
1234 private int state() {
1235 return state; // volatile read
1236 }
1237
1238 private void setState(int newValue) {
1239 state = newValue; // volatile write
1240 }
1241
1242 private boolean compareAndSetState(int expectedValue, int newValue) {
1243 return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1244 }
1245
1246 private void setParkPermit(boolean newValue) {
1247 if (parkPermit != newValue) {
1248 parkPermit = newValue;
1249 }
1250 }
1251
1252 private boolean getAndSetParkPermit(boolean newValue) {
1253 if (parkPermit != newValue) {
1254 return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1255 } else {
1256 return newValue;
1257 }
1258 }
1259
1260 private void setCarrierThread(Thread carrier) {
1261 // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1262 this.carrierThread = carrier;
1263 }
1264
1265 // -- JVM TI support --
1266
1267 @IntrinsicCandidate
1268 @JvmtiMountTransition
1269 private native void notifyJvmtiStart();
1270
1271 @IntrinsicCandidate
1272 @JvmtiMountTransition
1273 private native void notifyJvmtiEnd();
1274
1275 @IntrinsicCandidate
1276 @JvmtiMountTransition
1277 private native void notifyJvmtiMount(boolean hide);
1278
1279 @IntrinsicCandidate
1280 @JvmtiMountTransition
1281 private native void notifyJvmtiUnmount(boolean hide);
1282
1283 @IntrinsicCandidate
1284 @JvmtiMountTransition
1285 private static native void notifyJvmtiHideFrames(boolean hide);
1286
1287 @IntrinsicCandidate
1288 private static native void notifyJvmtiDisableSuspend(boolean enter);
1289
1290 private static native void registerNatives();
1291 static {
1292 registerNatives();
1293
1294 // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1295 var group = Thread.virtualThreadGroup();
1296
1297 // ensure VirtualThreadPinnedEvent is loaded/initialized
1298 U.ensureClassInitialized(VirtualThreadPinnedEvent.class);
1299 }
1300
1301 /**
1302 * Creates the default ForkJoinPool scheduler.
1303 */
1304 @SuppressWarnings("removal")
1305 private static ForkJoinPool createDefaultScheduler() {
1306 ForkJoinWorkerThreadFactory factory = pool -> {
1307 PrivilegedAction<ForkJoinWorkerThread> pa = () -> new CarrierThread(pool);
1308 return AccessController.doPrivileged(pa);
1309 };
1310 PrivilegedAction<ForkJoinPool> pa = () -> {
1311 int parallelism, maxPoolSize, minRunnable;
1312 String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1313 String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1314 String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1315 if (parallelismValue != null) {
1316 parallelism = Integer.parseInt(parallelismValue);
1317 } else {
1318 parallelism = Runtime.getRuntime().availableProcessors();
1319 }
1320 if (maxPoolSizeValue != null) {
1321 maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1322 parallelism = Integer.min(parallelism, maxPoolSize);
1323 } else {
1324 maxPoolSize = Integer.max(parallelism, 256);
1325 }
1359 }
1360 } else {
1361 int ncpus = Runtime.getRuntime().availableProcessors();
1362 queueCount = Math.max(Integer.highestOneBit(ncpus / 4), 1);
1363 }
1364 var schedulers = new ScheduledExecutorService[queueCount];
1365 for (int i = 0; i < queueCount; i++) {
1366 ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor)
1367 Executors.newScheduledThreadPool(1, task -> {
1368 Thread t = InnocuousThread.newThread("VirtualThread-unparker", task);
1369 t.setDaemon(true);
1370 return t;
1371 });
1372 stpe.setRemoveOnCancelPolicy(true);
1373 schedulers[i] = stpe;
1374 }
1375 return schedulers;
1376 }
1377
1378 /**
1379 * Reads the value of the jdk.tracePinnedThreads property to determine if stack
1380 * traces should be printed when a carrier thread is pinned when a virtual thread
1381 * attempts to park.
1382 */
1383 private static int tracePinningMode() {
1384 String propValue = GetPropertyAction.privilegedGetProperty("jdk.tracePinnedThreads");
1385 if (propValue != null) {
1386 if (propValue.length() == 0 || "full".equalsIgnoreCase(propValue))
1387 return 1;
1388 if ("short".equalsIgnoreCase(propValue))
1389 return 2;
1390 }
1391 return 0;
1392 }
1393 }
|
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.reflect.Constructor;
28 import java.security.AccessController;
29 import java.security.PrivilegedAction;
30 import java.util.Arrays;
31 import java.util.Locale;
32 import java.util.Objects;
33 import java.util.concurrent.Callable;
34 import java.util.concurrent.CountDownLatch;
35 import java.util.concurrent.Executor;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.ForkJoinPool;
38 import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;
39 import java.util.concurrent.ForkJoinTask;
40 import java.util.concurrent.ForkJoinWorkerThread;
41 import java.util.concurrent.Future;
42 import java.util.concurrent.RejectedExecutionException;
43 import java.util.concurrent.ScheduledExecutorService;
44 import java.util.concurrent.ScheduledThreadPoolExecutor;
45 import java.util.concurrent.TimeUnit;
46 import java.util.stream.Stream;
47 import jdk.internal.event.VirtualThreadEndEvent;
48 import jdk.internal.event.VirtualThreadStartEvent;
49 import jdk.internal.event.VirtualThreadSubmitFailedEvent;
50 import jdk.internal.misc.CarrierThread;
51 import jdk.internal.misc.InnocuousThread;
52 import jdk.internal.misc.Unsafe;
53 import jdk.internal.vm.Continuation;
54 import jdk.internal.vm.ContinuationScope;
55 import jdk.internal.vm.StackableScope;
56 import jdk.internal.vm.ThreadContainer;
57 import jdk.internal.vm.ThreadContainers;
58 import jdk.internal.vm.annotation.ChangesCurrentThread;
59 import jdk.internal.vm.annotation.Hidden;
60 import jdk.internal.vm.annotation.IntrinsicCandidate;
61 import jdk.internal.vm.annotation.JvmtiMountTransition;
62 import jdk.internal.vm.annotation.ReservedStackAccess;
63 import sun.nio.ch.Interruptible;
64 import sun.security.action.GetPropertyAction;
65 import static java.util.concurrent.TimeUnit.*;
66
67 /**
68 * A thread that is scheduled by the Java virtual machine rather than the operating system.
69 */
70 final class VirtualThread extends BaseVirtualThread {
71 private static final Unsafe U = Unsafe.getUnsafe();
72 private static final ContinuationScope VTHREAD_SCOPE = new ContinuationScope("VirtualThreads");
73 private static final Executor DEFAULT_SCHEDULER = createDefaultScheduler();
74 private static final ScheduledExecutorService[] DELAYED_TASK_SCHEDULERS = createDelayedTaskSchedulers();
75
76 private static final long STATE = U.objectFieldOffset(VirtualThread.class, "state");
77 private static final long PARK_PERMIT = U.objectFieldOffset(VirtualThread.class, "parkPermit");
78 private static final long CARRIER_THREAD = U.objectFieldOffset(VirtualThread.class, "carrierThread");
79 private static final long TERMINATION = U.objectFieldOffset(VirtualThread.class, "termination");
80 private static final long ON_WAITING_LIST = U.objectFieldOffset(VirtualThread.class, "onWaitingList");
81
82 // scheduler and continuation
83 private final Executor scheduler;
84 private final Continuation cont;
85 private final Runnable runContinuation;
86
87 // virtual thread state, accessed by VM
88 private volatile int state;
89
90 /*
91 * Virtual thread state transitions:
92 *
93 * NEW -> STARTED // Thread.start, schedule to run
94 * STARTED -> TERMINATED // failed to start
95 * STARTED -> RUNNING // first run
96 * RUNNING -> TERMINATED // done
97 *
98 * RUNNING -> PARKING // Thread parking with LockSupport.park
99 * PARKING -> PARKED // cont.yield successful, parked indefinitely
100 * PARKING -> PINNED // cont.yield failed, parked indefinitely on carrier
101 * PARKED -> UNPARKED // unparked, may be scheduled to continue
102 * PINNED -> RUNNING // unparked, continue execution on same carrier
103 * UNPARKED -> RUNNING // continue execution after park
104 *
105 * RUNNING -> TIMED_PARKING // Thread parking with LockSupport.parkNanos
106 * TIMED_PARKING -> TIMED_PARKED // cont.yield successful, timed-parked
107 * TIMED_PARKING -> TIMED_PINNED // cont.yield failed, timed-parked on carrier
108 * TIMED_PARKED -> UNPARKED // unparked, may be scheduled to continue
109 * TIMED_PINNED -> RUNNING // unparked, continue execution on same carrier
110 *
111 * RUNNING -> BLOCKING // blocking on monitor enter
112 * BLOCKING -> BLOCKED // blocked on monitor enter
113 * BLOCKED -> UNBLOCKED // unblocked, may be scheduled to continue
114 * UNBLOCKED -> RUNNING // continue execution after blocked on monitor enter
115 *
116 * RUNNING -> WAITING // transitional state during wait on monitor
117 * WAITING -> WAITED // waiting on monitor
118 * WAITED -> BLOCKED // notified, waiting to be unblocked by monitor owner
119 * WAITED -> UNBLOCKED // timed-out/interrupted
120 *
121 * RUNNING -> TIMED_WAITING // transition state during timed-waiting on monitor
122 * TIMED_WAITING -> TIMED_WAITED // timed-waiting on monitor
123 * TIMED_WAITED -> BLOCKED // notified, waiting to be unblocked by monitor owner
124 * TIMED_WAITED -> UNBLOCKED // timed-out/interrupted
125 *
126 * RUNNING -> YIELDING // Thread.yield
127 * YIELDING -> YIELDED // cont.yield successful, may be scheduled to continue
128 * YIELDING -> RUNNING // cont.yield failed
129 * YIELDED -> RUNNING // continue execution after Thread.yield
130 */
131 private static final int NEW = 0;
132 private static final int STARTED = 1;
133 private static final int RUNNING = 2; // runnable-mounted
134
135 // untimed and timed parking
136 private static final int PARKING = 3;
137 private static final int PARKED = 4; // unmounted
138 private static final int PINNED = 5; // mounted
139 private static final int TIMED_PARKING = 6;
140 private static final int TIMED_PARKED = 7; // unmounted
141 private static final int TIMED_PINNED = 8; // mounted
142 private static final int UNPARKED = 9; // unmounted but runnable
143
144 // Thread.yield
145 private static final int YIELDING = 10;
146 private static final int YIELDED = 11; // unmounted but runnable
147
148 // monitor enter
149 private static final int BLOCKING = 12;
150 private static final int BLOCKED = 13; // unmounted
151 private static final int UNBLOCKED = 14; // unmounted but runnable
152
153 // monitor wait/timed-wait
154 private static final int WAITING = 15;
155 private static final int WAIT = 16; // waiting in Object.wait
156 private static final int TIMED_WAITING = 17;
157 private static final int TIMED_WAIT = 18; // waiting in timed-Object.wait
158
159 private static final int TERMINATED = 99; // final state
160
161 // can be suspended from scheduling when unmounted
162 private static final int SUSPENDED = 1 << 8;
163
164 // parking permit
165 private volatile boolean parkPermit;
166
167 // used to mark thread as ready to be unblocked
168 private volatile boolean unblocked;
169
170 // notified by Object.notify/notifyAll while waiting in Object.wait
171 private volatile boolean notified;
172
173 // timed-wait support
174 private long waitTimeout;
175 private byte timedWaitNonce;
176 private volatile Future<?> waitTimeoutTask;
177
178 // a positive value if "responsible thread" blocked on monitor enter, accessed by VM
179 private volatile byte recheckInterval;
180
181 // carrier thread when mounted, accessed by VM
182 private volatile Thread carrierThread;
183
184 // termination object when joining, created lazily if needed
185 private volatile CountDownLatch termination;
186
187 // has the value 1 when on the list of virtual threads waiting to be unblocked
188 private volatile byte onWaitingList;
189
190 // next virtual thread on the list of virtual threads waiting to be unblocked
191 private volatile VirtualThread next;
192
193 /**
194 * Returns the default scheduler.
195 */
196 static Executor defaultScheduler() {
197 return DEFAULT_SCHEDULER;
198 }
199
200 /**
201 * Returns a stream of the delayed task schedulers used to support timed operations.
202 */
203 static Stream<ScheduledExecutorService> delayedTaskSchedulers() {
204 return Arrays.stream(DELAYED_TASK_SCHEDULERS);
205 }
206
207 /**
208 * Returns the continuation scope used for virtual threads.
209 */
210 static ContinuationScope continuationScope() {
211 return VTHREAD_SCOPE;
212 }
213
214 /**
215 * Creates a new {@code VirtualThread} to run the given task with the given
216 * scheduler. If the given scheduler is {@code null} and the current thread
217 * is a platform thread then the newly created virtual thread will use the
218 * default scheduler. If given scheduler is {@code null} and the current
219 * thread is a virtual thread then the current thread's scheduler is used.
220 *
221 * @param scheduler the scheduler or null
222 * @param name thread name
223 * @param characteristics characteristics
224 * @param task the task to execute
225 */
226 VirtualThread(Executor scheduler, String name, int characteristics, Runnable task) {
234 scheduler = vparent.scheduler;
235 } else {
236 scheduler = DEFAULT_SCHEDULER;
237 }
238 }
239
240 this.scheduler = scheduler;
241 this.cont = new VThreadContinuation(this, task);
242 this.runContinuation = this::runContinuation;
243 }
244
245 /**
246 * The continuation that a virtual thread executes.
247 */
248 private static class VThreadContinuation extends Continuation {
249 VThreadContinuation(VirtualThread vthread, Runnable task) {
250 super(VTHREAD_SCOPE, wrap(vthread, task));
251 }
252 @Override
253 protected void onPinned(Continuation.Pinned reason) {
254 // emit JFR event
255 virtualThreadPinnedEvent(reason.reasonCode(), reason.reasonString());
256 }
257 private static Runnable wrap(VirtualThread vthread, Runnable task) {
258 return new Runnable() {
259 @Hidden
260 public void run() {
261 vthread.run(task);
262 }
263 };
264 }
265 }
266
267 /**
268 * jdk.VirtualThreadPinned is emitted by HotSpot VM when pinned. Call into VM to
269 * emit event to avoid having a JFR event in Java with the same name (but different ID)
270 * to events emitted by the VM.
271 */
272 private static native void virtualThreadPinnedEvent(int reason, String reasonString);
273
274 /**
275 * Runs or continues execution on the current thread. The virtual thread is mounted
276 * on the current thread before the task runs or continues. It unmounts when the
277 * task completes or yields.
278 */
279 @ChangesCurrentThread // allow mount/unmount to be inlined
280 private void runContinuation() {
281 // the carrier must be a platform thread
282 if (Thread.currentThread().isVirtual()) {
283 throw new WrongThreadException();
284 }
285
286 // set state to RUNNING
287 int initialState = state();
288 if (initialState == STARTED || initialState == UNPARKED
289 || initialState == UNBLOCKED || initialState == YIELDED) {
290 // newly started or continue after parking/blocking/Thread.yield
291 if (!compareAndSetState(initialState, RUNNING)) {
292 return;
293 }
294 // consume parking permit when continuing after parking
295 if (initialState == UNPARKED) {
296 setParkPermit(false);
297 }
298 } else {
299 // not runnable
300 return;
301 }
302
303 mount();
304 try {
305 cont.run();
306 } finally {
307 unmount();
308 if (cont.isDone()) {
309 afterDone();
522 synchronized (interruptLock) {
523 setCarrierThread(null);
524 }
525 carrier.clearInterrupt();
526
527 // notify JVMTI after unmount
528 notifyJvmtiUnmount(/*hide*/false);
529 }
530
531 /**
532 * Sets the current thread to the current carrier thread.
533 */
534 @ChangesCurrentThread
535 @JvmtiMountTransition
536 private void switchToCarrierThread() {
537 notifyJvmtiHideFrames(true);
538 Thread carrier = this.carrierThread;
539 assert Thread.currentThread() == this
540 && carrier == Thread.currentCarrierThread();
541 carrier.setCurrentThread(carrier);
542 setLockId(this.threadId()); // keep lockid of vthread
543 }
544
545 /**
546 * Sets the current thread to the given virtual thread.
547 */
548 @ChangesCurrentThread
549 @JvmtiMountTransition
550 private static void switchToVirtualThread(VirtualThread vthread) {
551 Thread carrier = vthread.carrierThread;
552 assert carrier == Thread.currentCarrierThread();
553 carrier.setCurrentThread(vthread);
554 notifyJvmtiHideFrames(false);
555 }
556
557 /**
558 * Executes the given value returning task on the current carrier thread.
559 */
560 @ChangesCurrentThread
561 <V> V executeOnCarrierThread(Callable<V> task) throws Exception {
562 assert Thread.currentThread() == this;
610 } else {
611 submitRunContinuation();
612 }
613 }
614 return;
615 }
616
617 // Thread.yield
618 if (s == YIELDING) {
619 setState(YIELDED);
620
621 // external submit if there are no tasks in the local task queue
622 if (currentThread() instanceof CarrierThread ct && ct.getQueuedTaskCount() == 0) {
623 externalSubmitRunContinuation(ct.getPool());
624 } else {
625 submitRunContinuation();
626 }
627 return;
628 }
629
630 // blocking on monitorenter
631 if (s == BLOCKING) {
632 setState(BLOCKED);
633
634 // may have been unblocked while blocking
635 if (unblocked && compareAndSetState(BLOCKED, UNBLOCKED)) {
636 unblocked = false;
637 submitRunContinuation();
638 return;
639 }
640
641 // if thread is the designated responsible thread for a monitor then schedule
642 // it to wakeup so that it can check and recover. See objectMonitor.cpp.
643 int recheckInterval = this.recheckInterval;
644 if (recheckInterval > 0) {
645 assert recheckInterval >= 1 && recheckInterval <= 6;
646 // 4 ^ (recheckInterval - 1) = 1, 4, 16, ... 1024
647 long delay = 1 << (recheckInterval - 1) << (recheckInterval - 1);
648 schedule(this::unblock, delay, MILLISECONDS);
649 }
650 return;
651 }
652
653 // Object.wait
654 if (s == WAITING || s == TIMED_WAITING) {
655 byte nonce;
656 int newState;
657 if (s == WAITING) {
658 nonce = 0; // not used
659 setState(newState = WAIT);
660 } else {
661 // synchronize with timeout task (previous timed-wait may be running)
662 synchronized (timedWaitLock()) {
663 nonce = ++timedWaitNonce;
664 setState(newState = TIMED_WAIT);
665 }
666 }
667
668 // may have been notified while in transition to wait state
669 if (notified && compareAndSetState(newState, BLOCKED)) {
670 // may have even been unblocked already
671 if (unblocked && compareAndSetState(BLOCKED, UNBLOCKED)) {
672 unblocked = false;
673 submitRunContinuation();
674 }
675 return;
676 }
677
678 // may have been interrupted while in transition to wait state
679 if (interrupted && compareAndSetState(newState, UNBLOCKED)) {
680 submitRunContinuation();
681 return;
682 }
683
684 // schedule wakeup
685 if (newState == TIMED_WAIT) {
686 assert waitTimeout > 0;
687 waitTimeoutTask = schedule(() -> waitTimeoutExpired(nonce), waitTimeout, MILLISECONDS);
688 }
689 return;
690 }
691
692 assert false;
693 }
694
695 /**
696 * Invoked after the continuation completes.
697 */
698 private void afterDone() {
699 afterDone(true);
700 }
701
702 /**
703 * Invoked after the continuation completes (or start failed). Sets the thread
704 * state to TERMINATED and notifies anyone waiting for the thread to terminate.
705 *
706 * @param notifyContainer true if its container should be notified
707 */
708 private void afterDone(boolean notifyContainer) {
709 assert carrierThread == null;
710 setState(TERMINATED);
711
839 }
840
841 // park on carrier thread for remaining time when pinned
842 if (!yielded) {
843 long remainingNanos = nanos - (System.nanoTime() - startTime);
844 parkOnCarrierThread(true, remainingNanos);
845 }
846 }
847 }
848
849 /**
850 * Parks the current carrier thread up to the given waiting time or until
851 * unparked or interrupted. If the virtual thread is interrupted then the
852 * interrupt status will be propagated to the carrier thread.
853 * @param timed true for a timed park, false for untimed
854 * @param nanos the waiting time in nanoseconds
855 */
856 private void parkOnCarrierThread(boolean timed, long nanos) {
857 assert state() == RUNNING;
858
859 setState(timed ? TIMED_PINNED : PINNED);
860 try {
861 if (!parkPermit) {
862 if (!timed) {
863 U.park(false, 0);
864 } else if (nanos > 0) {
865 U.park(false, nanos);
866 }
867 }
868 } finally {
869 setState(RUNNING);
870 }
871
872 // consume parking permit
873 setParkPermit(false);
874 }
875
876 /**
877 * Invoked by parkNanos to schedule this virtual thread to be unparked after
878 * a given delay.
879 */
880 @ChangesCurrentThread
881 private Future<?> scheduleUnpark(long nanos) {
882 assert Thread.currentThread() == this;
883 // need to switch to current carrier thread to avoid nested parking
884 switchToCarrierThread();
885 try {
886 return schedule(this::unpark, nanos, NANOSECONDS);
887 } finally {
888 switchToVirtualThread(this);
889 }
890 }
891
892 /**
893 * Invoked by parkNanos to cancel the unpark timer.
894 */
895 @ChangesCurrentThread
896 private void cancel(Future<?> future) {
897 assert Thread.currentThread() == this;
898 if (!future.isDone()) {
899 // need to switch to current carrier thread to avoid nested parking
900 switchToCarrierThread();
901 try {
902 future.cancel(false);
903 } finally {
904 switchToVirtualThread(this);
905 }
906 }
907 }
908
909 /**
910 * Re-enables this virtual thread for scheduling. If this virtual thread is parked
911 * then its task is scheduled to continue, otherwise its next call to {@code park} or
912 * {@linkplain #parkNanos(long) parkNanos} is guaranteed not to block.
913 * @throws RejectedExecutionException if the scheduler cannot accept a task
925
926 // unparked while parked when pinned
927 if (s == PINNED || s == TIMED_PINNED) {
928 // unpark carrier thread when pinned
929 disableSuspendAndPreempt();
930 try {
931 synchronized (carrierThreadAccessLock()) {
932 Thread carrier = carrierThread;
933 if (carrier != null && ((s = state()) == PINNED || s == TIMED_PINNED)) {
934 U.unpark(carrier);
935 }
936 }
937 } finally {
938 enableSuspendAndPreempt();
939 }
940 return;
941 }
942 }
943 }
944
945 /**
946 * Invoked by unblocker thread to unblock this virtual thread.
947 */
948 private void unblock() {
949 assert !Thread.currentThread().isVirtual();
950 unblocked = true;
951 if (state() == BLOCKED && compareAndSetState(BLOCKED, UNBLOCKED)) {
952 unblocked = false;
953 submitRunContinuation();
954 }
955 }
956
957 /**
958 * Invoked by timer thread when wait timeout for virtual thread has expired.
959 * If the virtual thread is in timed-wait then this method will unblock the thread
960 * and submit its task so that it continues and attempts to reenter the monitor.
961 * This method does nothing if the thread has been woken by notify or interrupt.
962 */
963 private void waitTimeoutExpired(byte nounce) {
964 assert !Thread.currentThread().isVirtual();
965 for (;;) {
966 boolean unblocked = false;
967 synchronized (timedWaitLock()) {
968 if (nounce != timedWaitNonce) {
969 // this timeout task is for a past timed-wait
970 return;
971 }
972 int s = state();
973 if (s == TIMED_WAIT) {
974 unblocked = compareAndSetState(TIMED_WAIT, UNBLOCKED);
975 } else if (s != (TIMED_WAIT | SUSPENDED)) {
976 // notified or interrupted, no longer waiting
977 return;
978 }
979 }
980 if (unblocked) {
981 submitRunContinuation();
982 return;
983 }
984 // need to retry when thread is suspended in time-wait
985 Thread.yield();
986 }
987 }
988
989 /**
990 * Invoked by Object.wait to cancel the wait timer.
991 */
992 void cancelWaitTimeout() {
993 assert Thread.currentThread() == this;
994 Future<?> timeoutTask = this.waitTimeoutTask;
995 if (timeoutTask != null) {
996 // Pin the continuation to prevent the virtual thread from unmounting
997 // when there is contention removing the task. This avoids deadlock that
998 // could arise due to carriers and virtual threads contending for a
999 // lock on the delay queue.
1000 Continuation.pin();
1001 try {
1002 timeoutTask.cancel(false);
1003 } finally {
1004 Continuation.unpin();
1005 }
1006 }
1007 }
1008
1009 /**
1010 * Attempts to yield the current virtual thread (Thread.yield).
1011 */
1012 void tryYield() {
1013 assert Thread.currentThread() == this;
1014 setState(YIELDING);
1015 boolean yielded = false;
1016 try {
1017 yielded = yieldContinuation(); // may throw
1018 } finally {
1019 assert (Thread.currentThread() == this) && (yielded == (state() == RUNNING));
1020 if (!yielded) {
1021 assert state() == YIELDING;
1022 setState(RUNNING);
1023 }
1024 }
1025 }
1026
1027 /**
1028 * Sleep the current thread for the given sleep time (in nanoseconds). If
1119 if (blocker != null) {
1120 blocker.interrupt(this);
1121 }
1122
1123 // interrupt carrier thread if mounted
1124 Thread carrier = carrierThread;
1125 if (carrier != null) carrier.setInterrupt();
1126 }
1127 } finally {
1128 enableSuspendAndPreempt();
1129 }
1130
1131 // notify blocker after releasing interruptLock
1132 if (blocker != null) {
1133 blocker.postInterrupt();
1134 }
1135
1136 // make available parking permit, unpark thread if parked
1137 unpark();
1138
1139 // if thread is waiting in Object.wait then schedule to try to reenter
1140 int s = state();
1141 if ((s == WAIT || s == TIMED_WAIT) && compareAndSetState(s, UNBLOCKED)) {
1142 submitRunContinuation();
1143 }
1144
1145 } else {
1146 interrupted = true;
1147 carrierThread.setInterrupt();
1148 setParkPermit(true);
1149 }
1150 }
1151
1152 @Override
1153 public boolean isInterrupted() {
1154 return interrupted;
1155 }
1156
1157 @Override
1158 boolean getAndClearInterrupt() {
1159 assert Thread.currentThread() == this;
1160 boolean oldValue = interrupted;
1161 if (oldValue) {
1162 disableSuspendAndPreempt();
1163 try {
1164 synchronized (interruptLock) {
1172 return oldValue;
1173 }
1174
1175 @Override
1176 Thread.State threadState() {
1177 int s = state();
1178 switch (s & ~SUSPENDED) {
1179 case NEW:
1180 return Thread.State.NEW;
1181 case STARTED:
1182 // return NEW if thread container not yet set
1183 if (threadContainer() == null) {
1184 return Thread.State.NEW;
1185 } else {
1186 return Thread.State.RUNNABLE;
1187 }
1188 case UNPARKED:
1189 case YIELDED:
1190 // runnable, not mounted
1191 return Thread.State.RUNNABLE;
1192 case UNBLOCKED:
1193 // if designated responsible thread for monitor then thread is blocked
1194 if (isResponsibleForMonitor()) {
1195 return Thread.State.BLOCKED;
1196 } else {
1197 return Thread.State.RUNNABLE;
1198 }
1199 case RUNNING:
1200 // if designated responsible thread for monitor then thread is blocked
1201 if (isResponsibleForMonitor()) {
1202 return Thread.State.BLOCKED;
1203 }
1204 // if mounted then return state of carrier thread
1205 if (Thread.currentThread() != this) {
1206 disableSuspendAndPreempt();
1207 try {
1208 synchronized (carrierThreadAccessLock()) {
1209 Thread carrierThread = this.carrierThread;
1210 if (carrierThread != null) {
1211 return carrierThread.threadState();
1212 }
1213 }
1214 } finally {
1215 enableSuspendAndPreempt();
1216 }
1217 }
1218 // runnable, mounted
1219 return Thread.State.RUNNABLE;
1220 case PARKING:
1221 case TIMED_PARKING:
1222 case YIELDING:
1223 case WAITING:
1224 case TIMED_WAITING:
1225 // runnable, in transition
1226 return Thread.State.RUNNABLE;
1227 case PARKED:
1228 case PINNED:
1229 case WAIT:
1230 return State.WAITING;
1231 case TIMED_PARKED:
1232 case TIMED_PINNED:
1233 case TIMED_WAIT:
1234 return State.TIMED_WAITING;
1235 case BLOCKING:
1236 case BLOCKED:
1237 return State.BLOCKED;
1238 case TERMINATED:
1239 return Thread.State.TERMINATED;
1240 default:
1241 throw new InternalError();
1242 }
1243 }
1244
1245 /**
1246 * Returns true if thread is the designated responsible thread for a monitor.
1247 * See objectMonitor.cpp for details.
1248 */
1249 private boolean isResponsibleForMonitor() {
1250 return (recheckInterval > 0);
1251 }
1252
1253 @Override
1254 boolean alive() {
1255 int s = state;
1256 return (s != NEW && s != TERMINATED);
1257 }
1258
1259 @Override
1260 boolean isTerminated() {
1261 return (state == TERMINATED);
1262 }
1263
1264 @Override
1265 StackTraceElement[] asyncGetStackTrace() {
1266 StackTraceElement[] stackTrace;
1267 do {
1268 stackTrace = (carrierThread != null)
1269 ? super.asyncGetStackTrace() // mounted
1270 : tryGetStackTrace(); // unmounted
1271 if (stackTrace == null) {
1272 Thread.yield();
1273 }
1274 } while (stackTrace == null);
1275 return stackTrace;
1276 }
1277
1278 /**
1279 * Returns the stack trace for this virtual thread if it is unmounted.
1280 * Returns null if the thread is mounted or in transition.
1281 */
1282 private StackTraceElement[] tryGetStackTrace() {
1283 int initialState = state() & ~SUSPENDED;
1284 switch (initialState) {
1285 case NEW, STARTED, TERMINATED -> {
1286 return new StackTraceElement[0]; // unmounted, empty stack
1287 }
1288 case RUNNING, PINNED, TIMED_PINNED -> {
1289 return null; // mounted
1290 }
1291 case PARKED, TIMED_PARKED, BLOCKED, WAIT, TIMED_WAIT -> {
1292 // unmounted, not runnable
1293 }
1294 case UNPARKED, UNBLOCKED, YIELDED -> {
1295 // unmounted, runnable
1296 }
1297 case PARKING, TIMED_PARKING, BLOCKING, YIELDING, WAITING, TIMED_WAITING -> {
1298 return null; // in transition
1299 }
1300 default -> throw new InternalError("" + initialState);
1301 }
1302
1303 // thread is unmounted, prevent it from continuing
1304 int suspendedState = initialState | SUSPENDED;
1305 if (!compareAndSetState(initialState, suspendedState)) {
1306 return null;
1307 }
1308
1309 // get stack trace and restore state
1310 StackTraceElement[] stack;
1311 try {
1312 stack = cont.getStackTrace();
1313 } finally {
1314 assert state == suspendedState;
1315 setState(initialState);
1316 }
1317 boolean resubmit = switch (initialState) {
1318 case UNPARKED, UNBLOCKED, YIELDED -> {
1319 // resubmit as task may have run while suspended
1320 yield true;
1321 }
1322 case PARKED, TIMED_PARKED -> {
1323 // resubmit if unparked while suspended
1324 yield parkPermit && compareAndSetState(initialState, UNPARKED);
1325 }
1326 case BLOCKED -> {
1327 // resubmit if unblocked while suspended
1328 yield unblocked && compareAndSetState(BLOCKED, UNBLOCKED);
1329 }
1330 case WAIT, TIMED_WAIT -> {
1331 // resubmit if notified or interrupted while waiting (Object.wait)
1332 // waitTimeoutExpired will retry if the timed expired when suspended
1333 yield (notified || interrupted) && compareAndSetState(initialState, UNBLOCKED);
1334 }
1335 default -> throw new InternalError();
1336 };
1337 if (resubmit) {
1338 submitRunContinuation();
1339 }
1340 return stack;
1341 }
1342
1343 @Override
1344 public String toString() {
1345 StringBuilder sb = new StringBuilder("VirtualThread[#");
1346 sb.append(threadId());
1347 String name = getName();
1348 if (!name.isEmpty()) {
1349 sb.append(",");
1350 sb.append(name);
1351 }
1352 sb.append("]/");
1353
1354 // add the carrier state and thread name when mounted
1409 private CountDownLatch getTermination() {
1410 CountDownLatch termination = this.termination;
1411 if (termination == null) {
1412 termination = new CountDownLatch(1);
1413 if (!U.compareAndSetReference(this, TERMINATION, null, termination)) {
1414 termination = this.termination;
1415 }
1416 }
1417 return termination;
1418 }
1419
1420 /**
1421 * Returns the lock object to synchronize on when accessing carrierThread.
1422 * The lock prevents carrierThread from being reset to null during unmount.
1423 */
1424 private Object carrierThreadAccessLock() {
1425 // return interruptLock as unmount has to coordinate with interrupt
1426 return interruptLock;
1427 }
1428
1429 /**
1430 * Returns a lock object to coordinating timed-wait setup and timeout handling.
1431 */
1432 private Object timedWaitLock() {
1433 // use this object for now to avoid the overhead of introducing another lock
1434 return runContinuation;
1435 }
1436
1437 /**
1438 * Disallow the current thread be suspended or preempted.
1439 */
1440 private void disableSuspendAndPreempt() {
1441 notifyJvmtiDisableSuspend(true);
1442 Continuation.pin();
1443 }
1444
1445 /**
1446 * Allow the current thread be suspended or preempted.
1447 */
1448 private void enableSuspendAndPreempt() {
1449 Continuation.unpin();
1450 notifyJvmtiDisableSuspend(false);
1451 }
1452
1453 // -- wrappers for get/set of state, parking permit, and carrier thread --
1454
1455 private int state() {
1456 return state; // volatile read
1457 }
1458
1459 private void setState(int newValue) {
1460 state = newValue; // volatile write
1461 }
1462
1463 private boolean compareAndSetState(int expectedValue, int newValue) {
1464 return U.compareAndSetInt(this, STATE, expectedValue, newValue);
1465 }
1466
1467 private boolean compareAndSetOnWaitingList(byte expectedValue, byte newValue) {
1468 return U.compareAndSetByte(this, ON_WAITING_LIST, expectedValue, newValue);
1469 }
1470
1471 private void setParkPermit(boolean newValue) {
1472 if (parkPermit != newValue) {
1473 parkPermit = newValue;
1474 }
1475 }
1476
1477 private boolean getAndSetParkPermit(boolean newValue) {
1478 if (parkPermit != newValue) {
1479 return U.getAndSetBoolean(this, PARK_PERMIT, newValue);
1480 } else {
1481 return newValue;
1482 }
1483 }
1484
1485 private void setCarrierThread(Thread carrier) {
1486 // U.putReferenceRelease(this, CARRIER_THREAD, carrier);
1487 this.carrierThread = carrier;
1488 }
1489
1490 @IntrinsicCandidate
1491 private static native void setLockId(long tid);
1492
1493 // -- JVM TI support --
1494
1495 @IntrinsicCandidate
1496 @JvmtiMountTransition
1497 private native void notifyJvmtiStart();
1498
1499 @IntrinsicCandidate
1500 @JvmtiMountTransition
1501 private native void notifyJvmtiEnd();
1502
1503 @IntrinsicCandidate
1504 @JvmtiMountTransition
1505 private native void notifyJvmtiMount(boolean hide);
1506
1507 @IntrinsicCandidate
1508 @JvmtiMountTransition
1509 private native void notifyJvmtiUnmount(boolean hide);
1510
1511 @IntrinsicCandidate
1512 @JvmtiMountTransition
1513 private static native void notifyJvmtiHideFrames(boolean hide);
1514
1515 @IntrinsicCandidate
1516 private static native void notifyJvmtiDisableSuspend(boolean enter);
1517
1518 private static native void registerNatives();
1519 static {
1520 registerNatives();
1521
1522 // ensure VTHREAD_GROUP is created, may be accessed by JVMTI
1523 var group = Thread.virtualThreadGroup();
1524 }
1525
1526 /**
1527 * Creates the default scheduler.
1528 * If the system property {@code jdk.virtualThreadScheduler.implClass} is set then
1529 * its value is the name of a class that implements java.util.concurrent.Executor.
1530 * The class is public in an exported package, has a public no-arg constructor,
1531 * and is visible to the system class loader.
1532 * If the system property is not set then the default scheduler will be a
1533 * ForkJoinPool instance.
1534 */
1535 private static Executor createDefaultScheduler() {
1536 String propName = "jdk.virtualThreadScheduler.implClass";
1537 String propValue = GetPropertyAction.privilegedGetProperty(propName);
1538 if (propValue != null) {
1539 try {
1540 Class<?> clazz = Class.forName(propValue, true,
1541 ClassLoader.getSystemClassLoader());
1542 Constructor<?> ctor = clazz.getConstructor();
1543 return (Executor) ctor.newInstance();
1544 } catch (Exception ex) {
1545 throw new Error(ex);
1546 }
1547 } else {
1548 return createDefaultForkJoinPoolScheduler();
1549 }
1550 }
1551
1552 /**
1553 * Creates the default ForkJoinPool scheduler.
1554 */
1555 @SuppressWarnings("removal")
1556 private static ForkJoinPool createDefaultForkJoinPoolScheduler() {
1557 ForkJoinWorkerThreadFactory factory = pool -> {
1558 PrivilegedAction<ForkJoinWorkerThread> pa = () -> new CarrierThread(pool);
1559 return AccessController.doPrivileged(pa);
1560 };
1561 PrivilegedAction<ForkJoinPool> pa = () -> {
1562 int parallelism, maxPoolSize, minRunnable;
1563 String parallelismValue = System.getProperty("jdk.virtualThreadScheduler.parallelism");
1564 String maxPoolSizeValue = System.getProperty("jdk.virtualThreadScheduler.maxPoolSize");
1565 String minRunnableValue = System.getProperty("jdk.virtualThreadScheduler.minRunnable");
1566 if (parallelismValue != null) {
1567 parallelism = Integer.parseInt(parallelismValue);
1568 } else {
1569 parallelism = Runtime.getRuntime().availableProcessors();
1570 }
1571 if (maxPoolSizeValue != null) {
1572 maxPoolSize = Integer.parseInt(maxPoolSizeValue);
1573 parallelism = Integer.min(parallelism, maxPoolSize);
1574 } else {
1575 maxPoolSize = Integer.max(parallelism, 256);
1576 }
1610 }
1611 } else {
1612 int ncpus = Runtime.getRuntime().availableProcessors();
1613 queueCount = Math.max(Integer.highestOneBit(ncpus / 4), 1);
1614 }
1615 var schedulers = new ScheduledExecutorService[queueCount];
1616 for (int i = 0; i < queueCount; i++) {
1617 ScheduledThreadPoolExecutor stpe = (ScheduledThreadPoolExecutor)
1618 Executors.newScheduledThreadPool(1, task -> {
1619 Thread t = InnocuousThread.newThread("VirtualThread-unparker", task);
1620 t.setDaemon(true);
1621 return t;
1622 });
1623 stpe.setRemoveOnCancelPolicy(true);
1624 schedulers[i] = stpe;
1625 }
1626 return schedulers;
1627 }
1628
1629 /**
1630 * Schedule virtual threads that are ready to be scheduled after they blocked on
1631 * monitor enter.
1632 */
1633 private static void unblockVirtualThreads() {
1634 while (true) {
1635 VirtualThread vthread = takeVirtualThreadListToUnblock();
1636 while (vthread != null) {
1637 assert vthread.onWaitingList == 1;
1638 VirtualThread nextThread = vthread.next;
1639
1640 // remove from list and unblock
1641 vthread.next = null;
1642 boolean changed = vthread.compareAndSetOnWaitingList((byte) 1, (byte) 0);
1643 assert changed;
1644 vthread.unblock();
1645
1646 vthread = nextThread;
1647 }
1648 }
1649 }
1650
1651 /**
1652 * Retrieves the list of virtual threads that are waiting to be unblocked, waiting
1653 * if necessary until a list of one or more threads becomes available.
1654 */
1655 private static native VirtualThread takeVirtualThreadListToUnblock();
1656
1657 static {
1658 var unblocker = InnocuousThread.newThread("VirtualThread-unblocker",
1659 VirtualThread::unblockVirtualThreads);
1660 unblocker.setDaemon(true);
1661 unblocker.start();
1662 }
1663 }
|