-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathThread.java
More file actions
2847 lines (2639 loc) · 110 KB
/
Copy pathThread.java
File metadata and controls
2847 lines (2639 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1994, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import java.lang.ref.Reference;
import java.lang.reflect.Field;
import java.time.Duration;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.StructureViolationException;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
import jdk.internal.event.ThreadSleepEvent;
import jdk.internal.misc.TerminatingThreadLocal;
import jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
import jdk.internal.vm.Continuation;
import jdk.internal.vm.ScopedValueContainer;
import jdk.internal.vm.StackableScope;
import jdk.internal.vm.ThreadContainer;
import jdk.internal.vm.annotation.ForceInline;
import jdk.internal.vm.annotation.Hidden;
import jdk.internal.vm.annotation.IntrinsicCandidate;
import jdk.internal.vm.annotation.Stable;
import sun.nio.ch.Interruptible;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
/**
* A <i>thread</i> is a thread of execution in a program. The Java
* virtual machine allows an application to have multiple threads of
* execution running concurrently.
*
* <p> {@code Thread} defines constructors and a {@link Builder} to create threads.
* {@linkplain #start() Starting} a thread schedules it to execute its {@link #run() run}
* method. The newly started thread executes concurrently with the thread that caused
* it to start.
*
* <p> A thread <i>terminates</i> if either its {@code run} method completes normally,
* or if its {@code run} method completes abruptly and the appropriate {@linkplain
* Thread.UncaughtExceptionHandler uncaught exception handler} completes normally or
* abruptly. With no code left to run, the thread has completed execution. The {@link
* #isAlive isAlive} method can be used to test if a started thread has terminated.
* The {@link #join() join} method can be used to wait for a thread to terminate.
*
* <p> Threads have a unique {@linkplain #threadId() identifier} and a {@linkplain
* #getName() name}. The identifier is generated when a {@code Thread} is created
* and cannot be changed. The thread name can be specified when creating a thread
* or can be {@linkplain #setName(String) changed} at a later time.
*
* <p> Threads support {@link ThreadLocal} variables. These are variables that are
* local to a thread, meaning a thread can have a copy of a variable that is set to
* a value that is independent of the value set by other threads. {@code Thread} also
* supports {@link InheritableThreadLocal} variables that are thread local variables
* that are inherited at thread creation time from the parent {@code Thread}.
* {@code Thread} supports a special inheritable thread local for the thread
* {@linkplain #getContextClassLoader() context-class-loader}.
*
* <h2><a id="platform-threads">Platform Threads</a></h2>
* <p> {@code Thread} supports the creation of <i>platform threads</i> that are
* typically mapped 1:1 to kernel threads scheduled by the operating system.
* Platform threads will usually have a large stack and other resources that are
* maintained by the operating system. Platforms threads are suitable for executing
* all types of tasks but may be a limited resource.
*
* <p> Platform threads get an automatically generated thread name by default.
*
* <p> Platform threads are designated <i>daemon</i> or <i>non-daemon</i> threads.
* When the Java virtual machine starts up, there is usually one non-daemon
* thread (the thread that typically calls the application's {@code main} method).
* The <a href="Runtime.html#shutdown">shutdown sequence</a> begins when all started
* non-daemon threads have terminated. Unstarted non-daemon threads do not prevent
* the shutdown sequence from beginning.
*
* <p> In addition to the daemon status, platform threads have a {@linkplain
* #getPriority() thread priority} and are members of a {@linkplain ThreadGroup
* thread group}.
*
* <h2><a id="virtual-threads">Virtual Threads</a></h2>
* <p> {@code Thread} also supports the creation of <i>virtual threads</i>.
* Virtual threads are typically <i>user-mode threads</i> scheduled by the Java
* runtime rather than the operating system. Virtual threads will typically require
* few resources and a single Java virtual machine may support millions of virtual
* threads. Virtual threads are suitable for executing tasks that spend most of
* the time blocked, often waiting for I/O operations to complete. Virtual threads
* are not intended for long running CPU intensive operations.
*
* <p> Virtual threads typically employ a small set of platform threads used as
* <em>carrier threads</em>. Locking and I/O operations are examples of operations
* where a carrier thread may be re-scheduled from one virtual thread to another.
* Code executing in a virtual thread is not aware of the underlying carrier thread.
* The {@linkplain Thread#currentThread()} method, used to obtain a reference
* to the <i>current thread</i>, will always return the {@code Thread} object
* for the virtual thread.
*
* <p> Virtual threads do not have a thread name by default. The {@link #getName()
* getName} method returns the empty string if a thread name is not set.
*
* <p> Virtual threads are daemon threads and so do not prevent the
* <a href="Runtime.html#shutdown">shutdown sequence</a> from beginning.
* Virtual threads have a fixed {@linkplain #getPriority() thread priority}
* that cannot be changed.
*
* <h2>Creating And Starting Threads</h2>
*
* <p> {@code Thread} defines public constructors for creating platform threads and
* the {@link #start() start} method to schedule threads to execute. {@code Thread}
* may be extended for customization and other advanced reasons although most
* applications should have little need to do this.
*
* <p> {@code Thread} defines a {@link Builder} API for creating and starting both
* platform and virtual threads. The following are examples that use the builder:
* {@snippet :
* Runnable runnable = ...
*
* // Start a daemon thread to run a task
* Thread thread = Thread.ofPlatform().daemon().start(runnable);
*
* // Create an unstarted thread with name "duke", its start() method
* // must be invoked to schedule it to execute.
* Thread thread = Thread.ofPlatform().name("duke").unstarted(runnable);
*
* // A ThreadFactory that creates daemon threads named "worker-0", "worker-1", ...
* ThreadFactory factory = Thread.ofPlatform().daemon().name("worker-", 0).factory();
*
* // Start a virtual thread to run a task
* Thread thread = Thread.ofVirtual().start(runnable);
*
* // A ThreadFactory that creates virtual threads
* ThreadFactory factory = Thread.ofVirtual().factory();
* }
*
* <h2><a id="inheritance">Inheritance When Creating Threads</a></h2>
* A {@code Thread} created with one of the public constructors inherits the daemon
* status and thread priority from the parent thread at the time that the child {@code
* Thread} is created. The {@linkplain ThreadGroup thread group} is also inherited when
* not provided to the constructor. When using a {@code Thread.Builder} to create a
* platform thread, the daemon status, thread priority, and thread group are inherited
* when not set on the builder. As with the constructors, inheriting from the parent
* thread is done when the child {@code Thread} is created.
*
* <p> A {@code Thread} inherits its initial values of {@linkplain InheritableThreadLocal
* inheritable-thread-local} variables (including the context class loader) from
* the parent thread values at the time that the child {@code Thread} is created.
* The 5-param {@linkplain Thread#Thread(ThreadGroup, Runnable, String, long, boolean)
* constructor} can be used to create a thread that does not inherit its initial
* values from the constructing thread. When using a {@code Thread.Builder}, the
* {@link Builder#inheritInheritableThreadLocals(boolean) inheritInheritableThreadLocals}
* method can be used to select if the initial values are inherited.
*
* <h2><a id="thread-interruption">Thread Interruption</a></h2>
* A {@code Thread} has an <em>interrupted status</em> which serves as a "request" for
* code executing in the thread to "stop or cancel its current activity". The interrupted
* status is set by invoking the target thread's {@link #interrupt()} method. Many methods
* that cause a thread to block or wait are <em>interruptible</em>, meaning they detect
* that the thread's interrupted status is set and cause execution to return early from
* the method, usually by throwing an exception.
*
* <p> If a thread executing {@link #sleep(long) Thread.sleep} or {@link Object#wait()
* Object.wait} is interrupted then it causes the method to throw {@link InterruptedException}.
* Methods that throw {@code InterruptedException} do so after first clearing the
* interrupted status. Code that catches {@code InterruptedException} should rethrow the
* exception, or restore the current thread's interrupted status, with
* {@link #currentThread() Thread.currentThread()}.{@link #interrupt()}, before
* continuing normally or handling it by throwing another type of exception. Code that
* throws another type of exception with the {@code InterruptedException} as {@linkplain
* Throwable#getCause() cause}, or the {@code InterruptedException} as a {@linkplain
* Throwable#addSuppressed(Throwable) suppressed exception}, should also restore the
* interrupted status before throwing the exception.
*
* <p> If a thread executing a blocking I/O operation on an {@link
* java.nio.channels.InterruptibleChannel} is interrupted then it causes the channel to be
* closed, and the blocking I/O operation to throw {@link java.nio.channels.ClosedByInterruptException}
* with the thread's interrupted status set. If a thread blocked in a {@linkplain
* java.nio.channels.Selector selection operation} is interrupted then it causes the
* selection operation to return early, with the thread's interrupted status set.
*
* <p> Code that doesn't invoke any interruptible methods can still respond to interrupt
* by polling the current thread's interrupted status with
* {@link Thread#currentThread() Thread.currentThread()}.{@link #isInterrupted()
* isInterrupted()}.
*
* <p> In addition to the {@link #interrupt()} and {@link #isInterrupted()} methods,
* {@code Thread} also defines the static {@link #interrupted() Thread.interrupted()}
* method to test the current thread's interrupted status and clear it. It should be rare
* to need to use this method.
*
* <h2>Null Handling</h2>
* Unless otherwise specified, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be thrown.
*
* @implNote
* In the JDK Reference Implementation, the virtual thread scheduler may be configured
* with the following system properties:
* <table class="striped">
* <caption style="display:none">System properties</caption>
* <thead>
* <tr>
* <th scope="col">System property</th>
* <th scope="col">Description</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th scope="row">
* {@systemProperty jdk.virtualThreadScheduler.parallelism}
* </th>
* <td> The scheduler's target parallelism. This is the number of platform threads
* available for scheduling virtual threads. It defaults to the number of available
* processors. </td>
* </tr>
* <tr>
* <th scope="row">
* {@systemProperty jdk.virtualThreadScheduler.maxPoolSize}
* </th>
* <td> The maximum number of platform threads available to the scheduler.
* It defaults to 256. </td>
* </tr>
* </tbody>
* </table>
* <p> The virtual thread scheduler can be monitored and managed with the
* {@code jdk.management.VirtualThreadSchedulerMXBean} management interface.
*
* @since 1.0
*/
public class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
/*
* Reserved for exclusive use by the JVM. Cannot be moved to the FieldHolder
* as it needs to be set by the VM for JNI attaching threads, before executing
* the constructor that will create the FieldHolder. The historically named
* `eetop` holds the address of the underlying VM JavaThread, and is set to
* non-zero when the thread is started, and reset to zero when the thread terminates.
* A non-zero value indicates this thread isAlive().
*/
private volatile long eetop;
// thread id
private final long tid;
// thread name
private volatile String name;
// interrupted status (read/written by VM)
volatile boolean interrupted;
// context ClassLoader
private volatile ClassLoader contextClassLoader;
// Additional fields for platform threads.
// All fields, except task and terminatingThreadLocals, are accessed directly by the VM.
private static class FieldHolder {
final ThreadGroup group;
final Runnable task;
final long stackSize;
volatile int priority;
volatile boolean daemon;
volatile int threadStatus;
// Used by NativeThread for signalling
@Stable long nativeThreadID;
// This map is maintained by the ThreadLocal class
ThreadLocal.ThreadLocalMap terminatingThreadLocals;
FieldHolder(ThreadGroup group,
Runnable task,
long stackSize,
int priority,
boolean daemon) {
this.group = group;
this.task = task;
this.stackSize = stackSize;
this.priority = priority;
if (daemon)
this.daemon = true;
}
}
private final FieldHolder holder;
ThreadLocal.ThreadLocalMap terminatingThreadLocals() {
return holder.terminatingThreadLocals;
}
void setTerminatingThreadLocals(ThreadLocal.ThreadLocalMap map) {
holder.terminatingThreadLocals = map;
}
long nativeThreadID() {
return holder.nativeThreadID;
}
void setNativeThreadID(long id) {
holder.nativeThreadID = id;
}
/*
* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class.
*/
private ThreadLocal.ThreadLocalMap threadLocals;
ThreadLocal.ThreadLocalMap threadLocals() {
return threadLocals;
}
void setThreadLocals(ThreadLocal.ThreadLocalMap map) {
threadLocals = map;
}
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
private ThreadLocal.ThreadLocalMap inheritableThreadLocals;
ThreadLocal.ThreadLocalMap inheritableThreadLocals() {
return inheritableThreadLocals;
}
void setInheritableThreadLocals(ThreadLocal.ThreadLocalMap map) {
inheritableThreadLocals = map;
}
/*
* Scoped value bindings are maintained by the ScopedValue class.
*/
private Object scopedValueBindings;
// Special value to indicate this is a newly-created Thread
// Note that his must match the declaration in ScopedValue.
private static final Object NEW_THREAD_BINDINGS = Thread.class;
static Object scopedValueBindings() {
return currentThread().scopedValueBindings;
}
static void setScopedValueBindings(Object bindings) {
currentThread().scopedValueBindings = bindings;
}
/**
* Search the stack for the most recent scoped-value bindings.
*/
@IntrinsicCandidate
static native Object findScopedValueBindings();
/**
* Inherit the scoped-value bindings from the given container.
* Invoked when starting a thread.
*/
void inheritScopedValueBindings(ThreadContainer container) {
ScopedValueContainer.BindingsSnapshot snapshot;
if (container.owner() != null
&& (snapshot = container.scopedValueBindings()) != null) {
// bindings established for running/calling an operation
Object bindings = snapshot.scopedValueBindings();
if (currentThread().scopedValueBindings != bindings) {
throw new StructureViolationException("Scoped value bindings have changed");
}
this.scopedValueBindings = bindings;
}
}
/*
* Lock object for thread interrupt.
*/
final Object interruptLock = new Object();
/**
* The argument supplied to the current call to
* java.util.concurrent.locks.LockSupport.park.
* Set by (private) java.util.concurrent.locks.LockSupport.setBlocker
* Accessed using java.util.concurrent.locks.LockSupport.getBlocker
*/
private volatile Object parkBlocker;
/* The object in which this thread is blocked in an interruptible I/O
* operation, if any. The blocker's interrupt method should be invoked
* after setting this thread's interrupted status.
*/
private Interruptible nioBlocker;
Interruptible nioBlocker() {
//assert Thread.holdsLock(interruptLock);
return nioBlocker;
}
/* Set the blocker field; invoked via jdk.internal.access.SharedSecrets
* from java.nio code
*/
void blockedOn(Interruptible b) {
//assert Thread.currentThread() == this;
synchronized (interruptLock) {
nioBlocker = b;
}
}
/**
* The minimum priority that a thread can have.
*/
public static final int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public static final int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public static final int MAX_PRIORITY = 10;
/*
* Current inner-most continuation.
*/
private Continuation cont;
/**
* Returns the current continuation.
*/
Continuation getContinuation() {
return cont;
}
/**
* Sets the current continuation.
*/
void setContinuation(Continuation cont) {
this.cont = cont;
}
/**
* Returns the Thread object for the current platform thread. If the
* current thread is a virtual thread then this method returns the carrier.
*/
@IntrinsicCandidate
static native Thread currentCarrierThread();
/**
* Returns the Thread object for the current thread.
* @return the current thread
*/
@IntrinsicCandidate
public static native Thread currentThread();
/**
* Sets the Thread object to be returned by Thread.currentThread().
*/
@IntrinsicCandidate
native void setCurrentThread(Thread thread);
// ScopedValue support:
@IntrinsicCandidate
static native Object[] scopedValueCache();
@IntrinsicCandidate
static native void setScopedValueCache(Object[] cache);
@IntrinsicCandidate
static native void ensureMaterializedForStackWalk(Object o);
/**
* A hint to the scheduler that the current thread is willing to yield
* its current use of a processor. The scheduler is free to ignore this
* hint.
*
* <p> Yield is a heuristic attempt to improve relative progression
* between threads that would otherwise over-utilise a CPU. Its use
* should be combined with detailed profiling and benchmarking to
* ensure that it actually has the desired effect.
*
* <p> It is rarely appropriate to use this method. It may be useful
* for debugging or testing purposes, where it may help to reproduce
* bugs due to race conditions. It may also be useful when designing
* concurrency control constructs such as the ones in the
* {@link java.util.concurrent.locks} package.
*/
public static void yield() {
if (currentThread() instanceof VirtualThread vthread) {
vthread.tryYield();
} else {
yield0();
}
}
private static native void yield0();
/**
* Called before sleeping to create a jdk.ThreadSleep event.
*/
private static ThreadSleepEvent beforeSleep(long nanos) {
try {
ThreadSleepEvent event = new ThreadSleepEvent();
if (event.isEnabled()) {
event.time = nanos;
event.begin();
return event;
}
} catch (OutOfMemoryError e) {
// ignore
}
return null;
}
/**
* Called after sleeping to commit the jdk.ThreadSleep event.
*/
private static void afterSleep(ThreadSleepEvent event) {
if (event != null) {
try {
event.commit();
} catch (OutOfMemoryError e) {
// ignore
}
}
}
/**
* Sleep for the specified number of nanoseconds, subject to the precision
* and accuracy of system timers and schedulers.
*/
private static void sleepNanos(long nanos) throws InterruptedException {
ThreadSleepEvent event = beforeSleep(nanos);
try {
if (currentThread() instanceof VirtualThread vthread) {
vthread.sleepNanos(nanos);
} else {
sleepNanos0(nanos);
}
} finally {
afterSleep(event);
}
}
private static native void sleepNanos0(long nanos) throws InterruptedException;
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public static void sleep(long millis) throws InterruptedException {
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
long nanos = MILLISECONDS.toNanos(millis);
sleepNanos(nanos);
}
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds plus the specified
* number of nanoseconds, subject to the precision and accuracy of system
* timers and schedulers. The thread does not lose ownership of any
* monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @param nanos
* {@code 0-999999} additional nanoseconds to sleep
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative, or the value of
* {@code nanos} is not in the range {@code 0-999999}
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public static void sleep(long millis, int nanos) throws InterruptedException {
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException("nanosecond timeout value out of range");
}
// total sleep time, in nanoseconds
long totalNanos = MILLISECONDS.toNanos(millis);
totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos);
sleepNanos(totalNanos);
}
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified duration, subject to the precision and
* accuracy of system timers and schedulers. This method is a no-op if
* the duration is {@linkplain Duration#isNegative() negative}.
*
* @param duration
* the duration to sleep
*
* @throws InterruptedException
* if the current thread is interrupted while sleeping. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*
* @since 19
*/
public static void sleep(Duration duration) throws InterruptedException {
long nanos = NANOSECONDS.convert(duration); // MAX_VALUE if > 292 years
if (nanos < 0) {
return;
}
sleepNanos(nanos);
}
/**
* Indicates that the caller is momentarily unable to progress, until the
* occurrence of one or more actions on the part of other activities. By
* invoking this method within each iteration of a spin-wait loop construct,
* the calling thread indicates to the runtime that it is busy-waiting.
* The runtime may take action to improve the performance of invoking
* spin-wait loop constructions.
*
* @apiNote
* As an example consider a method in a class that spins in a loop until
* some flag is set outside of that method. A call to the {@code onSpinWait}
* method should be placed inside the spin loop.
* {@snippet :
* class EventHandler {
* volatile boolean eventNotificationNotReceived;
* void waitForEventAndHandleIt() {
* while ( eventNotificationNotReceived ) {
* Thread.onSpinWait();
* }
* readAndProcessEvent();
* }
*
* void readAndProcessEvent() {
* // Read event from some source and process it
* . . .
* }
* }
* }
* <p>
* The code above would remain correct even if the {@code onSpinWait}
* method was not called at all. However on some architectures the Java
* Virtual Machine may issue the processor instructions to address such
* code patterns in a more beneficial way.
*
* @since 9
*/
@IntrinsicCandidate
public static void onSpinWait() {}
/**
* Characteristic value signifying that initial values for {@link
* InheritableThreadLocal inheritable-thread-locals} are not inherited from
* the constructing thread.
* See Thread initialization.
*/
static final int NO_INHERIT_THREAD_LOCALS = 1 << 2;
/**
* Thread identifier assigned to the primordial thread.
*/
static final long PRIMORDIAL_TID = 3;
/**
* Helper class to generate thread identifiers. The identifiers start at
* {@link Thread#PRIMORDIAL_TID} +1 as this class cannot be used during
* early startup to generate the identifier for the primordial thread. The
* counter is off-heap and shared with the VM to allow it to assign thread
* identifiers to non-Java threads.
* See Thread initialization.
*/
private static class ThreadIdentifiers {
private static final Unsafe U;
private static final long NEXT_TID_OFFSET;
static {
U = Unsafe.getUnsafe();
NEXT_TID_OFFSET = Thread.getNextThreadIdOffset();
}
static long next() {
return U.getAndAddLong(null, NEXT_TID_OFFSET, 1);
}
}
/**
* Initializes a platform Thread.
*
* @param g the Thread group, can be null
* @param name the name of the new Thread
* @param characteristics thread characteristics
* @param task the object whose run() method gets called
* @param stackSize the desired stack size for the new thread, or
* zero to indicate that this parameter is to be ignored.
*/
Thread(ThreadGroup g, String name, int characteristics, Runnable task, long stackSize) {
Thread parent = currentThread();
boolean attached = (parent == this); // primordial or JNI attached
if (attached) {
if (g == null) {
throw new InternalError("group cannot be null when attaching");
}
this.holder = new FieldHolder(g, task, stackSize, NORM_PRIORITY, false);
} else {
if (g == null) {
// default to current thread's group
g = parent.getThreadGroup();
}
int priority = Math.min(parent.getPriority(), g.getMaxPriority());
this.holder = new FieldHolder(g, task, stackSize, priority, parent.isDaemon());
}
if (attached && VM.initLevel() < 1) {
this.tid = PRIMORDIAL_TID; // primordial thread
} else {
this.tid = ThreadIdentifiers.next();
}
this.name = (name != null) ? name : genThreadName();
// thread locals
if (!attached) {
if ((characteristics & NO_INHERIT_THREAD_LOCALS) == 0) {
ThreadLocal.ThreadLocalMap parentMap = parent.inheritableThreadLocals;
if (parentMap != null && parentMap.size() > 0) {
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parentMap);
}
if (VM.isBooted()) {
this.contextClassLoader = parent.getContextClassLoader();
}
} else if (VM.isBooted()) {
// default CCL to the system class loader when not inheriting
this.contextClassLoader = ClassLoader.getSystemClassLoader();
}
}
// special value to indicate this is a newly-created Thread
// Note that his must match the declaration in ScopedValue.
this.scopedValueBindings = NEW_THREAD_BINDINGS;
}
/**
* Initializes a virtual Thread.
*
* @param name thread name, can be null
* @param characteristics thread characteristics
* @param bound true when bound to an OS thread
*/
Thread(String name, int characteristics, boolean bound) {
this.tid = ThreadIdentifiers.next();
this.name = (name != null) ? name : "";
// thread locals
if ((characteristics & NO_INHERIT_THREAD_LOCALS) == 0) {
Thread parent = currentThread();
ThreadLocal.ThreadLocalMap parentMap = parent.inheritableThreadLocals;
if (parentMap != null && parentMap.size() > 0) {
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parentMap);
}
this.contextClassLoader = parent.getContextClassLoader();
} else {
// default CCL to the system class loader when not inheriting
this.contextClassLoader = ClassLoader.getSystemClassLoader();
}
// special value to indicate this is a newly-created Thread
this.scopedValueBindings = NEW_THREAD_BINDINGS;
// create a FieldHolder object, needed when bound to an OS thread
if (bound) {
ThreadGroup g = Constants.VTHREAD_GROUP;
int pri = NORM_PRIORITY;
this.holder = new FieldHolder(g, null, -1, pri, true);
} else {
this.holder = null;
}
}
/**
* The task that a {@linkplain VirtualThreadScheduler virtual thread scheduler}
* executes on a platform thread to
* {@linkplain VirtualThreadScheduler#onStart(VirtualThreadTask) start}
* or {@linkplain VirtualThreadScheduler#onContinue(VirtualThreadTask) continue}
* execution of a virtual thread. While executing the task, the platform thread is
* the virtual thread's <em>carrier</em>.
*
* <p> There is a {@code VirtualThreadTask} object for each virtual thread. The
* scheduler arranges to execute its {@link #run()} method when called to start or
* continue the virtual thread, if possible on the {@linkplain #preferredCarrier()
* preferred carrier thread}. The scheduler may attach an object to the task.
*
* @since 99
*/
public sealed interface VirtualThreadTask extends Runnable permits VirtualThread.VThreadTask {
/**
* {@return the virtual thread that this task starts or continues}
*/
Thread thread();
/**
* Runs the task on the current thread as the carrier thread.
*
* <p> Invoking this method with the interrupted status set will first
* clear the interrupt status. Interrupting the carrier thread while
* running the task leads to unspecified behavior.
*
* @throws IllegalStateException if the virtual thread is not in a state to
* run on the current thread
* @throws IllegalCallerException if the current thread is a virtual thread
*/
@Override
void run();
/**
* Returns the preferred carrier thread to execute this task. The scheduler may
* choose to ignore this preference.
* @return the preferred carrier thread or {@code null} if there is no preferred
* carrier thread
*/
Thread preferredCarrier();
/**
* Attaches the given object to this task.
* @param att the object to attach
* @return the previously-attached object, if any, otherwise {@code null}
*/
Object attach(Object att);
/**
* Retrieves the current attachment.
* @return the object currently attached to this task or {@code null} if
* there is no attachment
*/
Object attachment();
}
/**
* Virtual thread scheduler.
*
* @apiNote The following example creates a virtual thread scheduler that uses a small
* set of platform threads.
* {@snippet lang=java :
* ExecutorService threadPool = Executors.newFixedThreadPool(4);
* var scheduler = new VirtualThreadScheduler() {
* private void submit(VirtualThreadTask task) {
* Thread caller = Thread.currentThread();
* threadPool.submit(() -> {
* Thread vthread = task.thread();
* Thread carrier = Thread.currentThread();
* try {
* task.run();
* } finally {
* assert Thread.currentThread() == carrier;
* boolean terminated = !vthread.isAlive();
* }
* });
* }
* @Override
* public void onStart(VirtualThreadTask task) {
* submit(task);
* }
* @Override
* public void onContinue(VirtualThreadTask task) {
* submit(task);
* }
* };
* }
*
* <p> Unless otherwise specified, passing a null argument to a method in
* this interface causes a {@code NullPointerException} to be thrown.
*
* @since 99
*/
public interface VirtualThreadScheduler {
/**
* Invoked by {@link Thread#start()} to start execution of a {@linkplain
* VirtualThreadTask#thread() virtual thread}.
* The scheduler's implementation of this method must arrange to execute the
* given task's {@link VirtualThreadTask#run() run()} method on a platform thread.
*
* @implNote If invoked from a virtual thread, then the caller virtual thread is
* <em>pinned</em> to its carrier while executing the {@code onStart} method.
*
* @param task the task to execute
* @throws RejectedExecutionException if the scheduler cannot accept the task
*/
void onStart(VirtualThreadTask task);
/**
* Invoked to continue execution of a {@linkplain VirtualThreadTask#thread()
* virtual thread}.
* The scheduler's implementation of this method must arrange to execute the
* given task's {@link VirtualThreadTask#run() run()} method on a platform thread.
*
* @implNote If invoked from a virtual thread, then the caller virtual thread is
* <em>pinned</em> to its carrier while executing the {@code onContinue} method.
*
* @param task the task to execute
* @throws RejectedExecutionException if the scheduler cannot accept the task
*/
void onContinue(VirtualThreadTask task);
/**
* Creates a new virtual thread, returning the {@code VirtualThreadTask} that the
* virtual thread scheduler arranges to execute on a platform thread to start or
* continue execution of the virtual thread.
*
* <p> This method creates a new unstarted {@code Thread} from the current state
* of the given builder to run the given task. The {@link VirtualThreadTask#thread()
* thread()} method returns the virtual threa. The thread's {@link Thread#start()
* start()} method must be invoked to schedule the thread to begin execution.
*
* @apiNote This method is intended for frameworks that make use of a custom
* {@link VirtualThreadScheduler VirtualThreadScheduler} and wish to specify a
* preferred carrier thread when creating a virtual thread, or need a reference
* to the virtual thread task before the virtual thread is started. The
* framework can use the {@link VirtualThreadTask#attach(Object) attach(Object)}
* method to attach its context object to the task before the thread is started.
*
* @implSpec The default implementation creates a new virtual thread. It should
* be rare to override this method.
*
* @param name the thread name, can be {@code null}
* @param characteristics the thread characteristics
* @param preferredCarrier the preferred carrier, can be {@code null}
* @param task the object to run when the thread executes
* @return the {@code VirtualThreadTask} that scheduler executes
* @throws UnsupportedOperationException if this is the built-in default scheduler
*/
default VirtualThreadTask newThread(String name, int characteristics,
Thread preferredCarrier,
Runnable task) {
Objects.requireNonNull(task);
if (this == VirtualThread.builtinScheduler(false)) {
throw new UnsupportedOperationException();
}
var vthread = new VirtualThread(this, preferredCarrier, name, characteristics, task);
return vthread.virtualThreadTask();
}
/**
* Creates a new virtual thread using the given builder's configuration.
* Delegates to {@link #newThread(String, int, Thread, Runnable)}.
*
* @param builder the virtual thread builder
* @param preferredCarrier the preferred carrier, can be {@code null}
* @param task the object to run when the thread executes
* @return the {@code VirtualThreadTask} that scheduler executes
*/
default VirtualThreadTask newThread(Builder.OfVirtual builder,
Thread preferredCarrier,
Runnable task) {