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