-
Notifications
You must be signed in to change notification settings - Fork 27
/
Thread.java
3347 lines (3121 loc) · 132 KB
/
Thread.java
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, 2022, 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.
*/
/*
* ===========================================================================
* (c) Copyright IBM Corp. 2021, 2022 All Rights Reserved
* ===========================================================================
*/
package java.lang;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.time.Duration;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.locks.LockSupport;
import java.util.function.Predicate;
import java.util.stream.Stream;
import jdk.internal.event.ThreadSleepEvent;
import jdk.internal.javac.PreviewFeature;
import jdk.internal.misc.PreviewFeatures;
import jdk.internal.misc.StructureViolationExceptions;
import jdk.internal.misc.TerminatingThreadLocal;
import jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
import jdk.internal.vm.Continuation;
import jdk.internal.vm.ExtentLocalContainer;
import jdk.internal.vm.StackableScope;
import jdk.internal.vm.ThreadContainer;
import jdk.internal.vm.annotation.IntrinsicCandidate;
import jdk.internal.vm.annotation.Stable;
import sun.nio.ch.Interruptible;
import sun.security.util.SecurityConstants;
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
* that execute {@link Runnable} tasks. {@linkplain #start() Starting} a thread
* schedules it to execute concurrently with the thread that caused it to start.
* The newly started thread invokes the task's {@link Runnable#run() run} method.
* Thread defines the {@link #join() join} method 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. Thread also supports
* {@link InheritableThreadLocal} variables that are thread local variables that are
* inherited at Thread creation time from the parent Thread. 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 Java virtual machine terminates when all started non-daemon threads have
* terminated. Unstarted non-daemon threads do not prevent the Java virtual machine
* from terminating. The Java virtual machine can also be terminated by invoking
* the {@linkplain Runtime#exit(int)} method, in which case it will terminate even
* if there are non-daemon threads still running.
*
* <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 Java virtual
* machine from terminating. 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} 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.
*
* <p> Platform threads inherit the daemon status, thread priority, and when not
* provided (or not selected by a security manager), the thread group.
*
* <p> Inherited Access Control Context:
* Creating a platform thread {@linkplain AccessController#getContext() captures} the
* {@linkplain AccessControlContext caller context} to limit the {@linkplain Permission
* permissions} of {@linkplain AccessController#doPrivileged(PrivilegedAction) privileged
* actions} performed by code in the thread. Creating a virtual thread does not capture
* the caller context; virtual threads have no permissions when executing code that
* performs privileged actions.
*
* <p> 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 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>
*
* @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, maybe move to FieldHolder */
private long eetop;
// thread id
private final long tid;
// thread name
private volatile String name;
// interrupt status (read/written by VM)
volatile boolean interrupted;
// context ClassLoader
private volatile ClassLoader contextClassLoader;
// inherited AccessControlContext, this could be moved to FieldHolder
@SuppressWarnings("removal")
private AccessControlContext inheritedAccessControlContext;
// Additional fields for platform threads.
// All fields, except task, 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;
boolean stillborn;
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 values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals;
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals;
/*
* Extent locals binding are maintained by the ExtentLocal class.
*/
private Object extentLocalBindings;
static Object extentLocalBindings() {
return currentThread().extentLocalBindings;
}
static void setExtentLocalBindings(Object bindings) {
currentThread().extentLocalBindings = bindings;
}
/**
* Inherit the extent-local bindings from the given container.
* Invoked when starting a thread.
*/
void inheritExtentLocalBindings(ThreadContainer container) {
ExtentLocalContainer.BindingsSnapshot snapshot;
if (container.owner() != null
&& (snapshot = container.extentLocalBindings()) != null) {
// bindings established for running/calling an operation
Object bindings = snapshot.extentLocalBindings();
if (currentThread().extentLocalBindings != bindings) {
StructureViolationExceptions.throwException("Extent local bindings have changed");
}
this.extentLocalBindings = 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 interrupt status.
*/
volatile Interruptible nioBlocker;
/* Set the blocker field; invoked via jdk.internal.access.SharedSecrets
* from java.nio code
*/
static void blockedOn(Interruptible b) {
Thread me = Thread.currentThread();
synchronized (me.interruptLock) {
me.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);
// ExtentLocal support:
@IntrinsicCandidate
static native Object[] extentLocalCache();
@IntrinsicCandidate
static native void setExtentLocalCache(Object[] cache);
/**
* 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();
/**
* 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");
}
if (currentThread() instanceof VirtualThread vthread) {
long nanos = MILLISECONDS.toNanos(millis);
vthread.sleepNanos(nanos);
return;
}
if (ThreadSleepEvent.isTurnedOn()) {
ThreadSleepEvent event = new ThreadSleepEvent();
try {
event.time = MILLISECONDS.toNanos(millis);
event.begin();
sleep0(millis);
} finally {
event.commit();
}
} else {
sleep0(millis);
}
}
private static void sleep0(long millis) throws InterruptedException {
sleepImpl(millis, 0);
}
private static native void sleepImpl(long millis, int 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");
}
if (currentThread() instanceof VirtualThread vthread) {
// total sleep time, in nanoseconds
long totalNanos = MILLISECONDS.toNanos(millis);
totalNanos += Math.min(Long.MAX_VALUE - totalNanos, nanos);
vthread.sleepNanos(totalNanos);
return;
}
if (nanos > 0 && millis < Long.MAX_VALUE) {
millis++;
}
sleep(millis);
}
/**
* 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;
if (currentThread() instanceof VirtualThread vthread) {
vthread.sleepNanos(nanos);
return;
}
// convert to milliseconds
long millis = MILLISECONDS.convert(nanos, NANOSECONDS);
if (nanos > NANOSECONDS.convert(millis, MILLISECONDS)) {
millis += 1L;
}
sleep(millis);
}
/**
* 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 the thread cannot set values for its
* copy of {@link ThreadLocal thread-locals}.
* See Thread initialization.
*/
static final int NO_THREAD_LOCALS = 1 << 1;
/**
* 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;
/**
* Helper class to generate thread identifiers. The identifiers start at
* 2 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 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);
}
}
/**
* Returns the context class loader to inherit from the parent thread.
* See Thread initialization.
*/
private static ClassLoader contextClassLoader(Thread parent) {
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm == null || isCCLOverridden(parent.getClass())) {
return parent.getContextClassLoader();
} else {
// skip call to getContextClassLoader
ClassLoader cl = parent.contextClassLoader;
return (isSupportedClassLoader(cl)) ? cl : ClassLoader.getSystemClassLoader();
}
}
/**
* 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.
* @param acc the AccessControlContext to inherit, or
* AccessController.getContext() if null
*/
@SuppressWarnings("removal")
Thread(ThreadGroup g, String name, int characteristics, Runnable task,
long stackSize, AccessControlContext acc) {
if (name == null) {
throw new InternalError("name cannot be null");
}
Thread parent = currentThread();
boolean attached = (parent == this); // primordial or JNI attached
if (attached && g == null) {
throw new InternalError("group cannot be null when attaching");
}
SecurityManager security = System.getSecurityManager();
if (g == null) {
// the security manager can choose the thread group
if (security != null) {
g = security.getThreadGroup();
}
// default to current thread's group
if (g == null) {
g = parent.getThreadGroup();
}
}
initialize(false, g, parent, acc, characteristics);
if (attached && VM.initLevel() < 1) {
this.tid = 1; // primordial thread
} else {
this.tid = ThreadIdentifiers.next();
}
this.name = name;
int priority;
boolean daemon;
if (attached) {
// primordial or attached thread
priority = NORM_PRIORITY;
daemon = false;
} else {
priority = Math.min(parent.getPriority(), g.getMaxPriority());
daemon = parent.isDaemon();
}
this.holder = new FieldHolder(g, task, stackSize, priority, daemon);
}
/**
* 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 : "";
this.inheritedAccessControlContext = Constants.NO_PERMISSIONS_ACC;
// thread locals
if ((characteristics & NO_THREAD_LOCALS) != 0) {
this.threadLocals = ThreadLocal.ThreadLocalMap.NOT_SUPPORTED;
this.inheritableThreadLocals = ThreadLocal.ThreadLocalMap.NOT_SUPPORTED;
this.contextClassLoader = Constants.NOT_SUPPORTED_CLASSLOADER;
} else if ((characteristics & NO_INHERIT_THREAD_LOCALS) == 0) {
Thread parent = currentThread();
ThreadLocal.ThreadLocalMap parentMap = parent.inheritableThreadLocals;
if (parentMap != null
&& parentMap != ThreadLocal.ThreadLocalMap.NOT_SUPPORTED
&& parentMap.size() > 0) {
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parentMap);
}
ClassLoader parentLoader = contextClassLoader(parent);
if (isSupportedClassLoader(parentLoader)) {
this.contextClassLoader = parentLoader;
} else {
// parent does not support thread locals so no CCL to inherit
this.contextClassLoader = ClassLoader.getSystemClassLoader();
}
} else {
// default CCL to the system class loader when not inheriting
this.contextClassLoader = ClassLoader.getSystemClassLoader();
}
// 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;
}
}
/**
* Returns a builder for creating a platform {@code Thread} or {@code ThreadFactory}
* that creates platform threads.
*
* <p> <a id="ofplatform-security"><b>Interaction with security manager when
* creating platform threads</b></a>
* <p> Creating a platform thread when there is a security manager set will
* invoke the security manager's {@link SecurityManager#checkAccess(ThreadGroup)
* checkAccess(ThreadGroup)} method with the thread's thread group.
* If the thread group has not been set with the {@link
* Builder.OfPlatform#group(ThreadGroup) OfPlatform.group} method then the
* security manager's {@link SecurityManager#getThreadGroup() getThreadGroup}
* method will be invoked first to select the thread group. If the security
* manager {@code getThreadGroup} method returns {@code null} then the thread
* group of the constructing thread is used.
*
* @apiNote The following are examples using the builder:
* {@snippet :
* // 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();
* }
*
* @return A builder for creating {@code Thread} or {@code ThreadFactory} objects.
* @since 19
*/
@PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
public static Builder.OfPlatform ofPlatform() {
return new ThreadBuilders.PlatformThreadBuilder();
}
/**
* Returns a builder for creating a virtual {@code Thread} or {@code ThreadFactory}
* that creates virtual threads.
*
* @apiNote The following are examples using the builder:
* {@snippet :
* // 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();
* }
*
* @return A builder for creating {@code Thread} or {@code ThreadFactory} objects.
* @throws UnsupportedOperationException if preview features are not enabled
* @since 19
*/
@PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
public static Builder.OfVirtual ofVirtual() {
PreviewFeatures.ensureEnabled();
return new ThreadBuilders.VirtualThreadBuilder();
}
/**
* A builder for {@link Thread} and {@link ThreadFactory} objects.
*
* <p> {@code Builder} defines methods to set {@code Thread} properties such
* as the thread {@link #name(String) name}. This includes properties that would
* otherwise be <a href="Thread.html#inheritance">inherited</a>. Once set, a
* {@code Thread} or {@code ThreadFactory} is created with the following methods:
*
* <ul>
* <li> The {@linkplain #unstarted(Runnable) unstarted} method creates a new
* <em>unstarted</em> {@code Thread} to run a task. The {@code Thread}'s
* {@link Thread#start() start} method must be invoked to schedule the
* thread to execute.
* <li> The {@linkplain #start(Runnable) start} method creates a new {@code
* Thread} to run a task and schedules the thread to execute.
* <li> The {@linkplain #factory() factory} method creates a {@code ThreadFactory}.
* </ul>
*
* <p> A {@code Thread.Builder} is not thread safe. The {@code ThreadFactory}
* returned by the builder's {@code factory()} method is thread safe.
*
* <p> Unless otherwise specified, passing a null argument to a method in
* this interface causes a {@code NullPointerException} to be thrown.
*
* @see Thread#ofPlatform()
* @see Thread#ofVirtual()
* @since 19
*/
@PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
public sealed interface Builder
permits Builder.OfPlatform,
Builder.OfVirtual,
ThreadBuilders.BaseThreadBuilder {
/**
* Sets the thread name.
* @param name thread name
* @return this builder
*/
Builder name(String name);
/**
* Sets the thread name to be the concatenation of a string prefix and
* the string representation of a counter value. The counter's initial
* value is {@code start}. It is incremented after a {@code Thread} is
* created with this builder so that the next thread is named with
* the new counter value. A {@code ThreadFactory} created with this
* builder is seeded with the current value of the counter. The {@code
* ThreadFactory} increments its copy of the counter after {@link
* ThreadFactory#newThread(Runnable) newThread} is used to create a
* {@code Thread}.
*
* @apiNote
* The following example creates a builder that is invoked twice to start
* two threads named "{@code worker-0}" and "{@code worker-1}".
* {@snippet :
* Thread.Builder builder = Thread.ofPlatform().name("worker-", 0);
* Thread t1 = builder.start(task1); // name "worker-0"
* Thread t2 = builder.start(task2); // name "worker-1"
* }
*
* @param prefix thread name prefix
* @param start the starting value of the counter
* @return this builder
* @throws IllegalArgumentException if start is negative
*/
Builder name(String prefix, long start);
/**
* Sets whether the thread is allowed to set values for its copy of {@linkplain
* ThreadLocal thread-local} variables. The default is to allow. If not allowed,
* then any attempt by the thread to set a value for a thread-local with the
* {@link ThreadLocal#set(Object)} method throws {@code
* UnsupportedOperationException}. Any attempt to set the thread's context
* class loader with {@link Thread#setContextClassLoader(ClassLoader)
* setContextClassLoader} also throws. The {@link ThreadLocal#get()} method
* always returns the {@linkplain ThreadLocal#initialValue() initial-value}
* when thread locals are not allowed.
*
* @apiNote This method is intended for cases where there are a large number of
* threads and where potentially unbounded memory usage due to thread locals is
* a concern. Disallowing a thread to set its copy of thread-local variables
* creates the potential for exceptions at run-time so great care is required
* when the thread is used to invoke arbitrary code.
*
* @param allow {@code true} to allow, {@code false} to disallow
* @return this builder
*/
Builder allowSetThreadLocals(boolean allow);
/**
* Sets whether the thread inherits the initial values of {@linkplain
* InheritableThreadLocal inheritable-thread-local} variables from the
* constructing thread. The default is to inherit.
*
* <p> The initial values of {@code InheritableThreadLocal}s are never inherited
* when {@link #allowSetThreadLocals(boolean)} is used to disallow the thread
* to have its own copy of thread-local variables.
*
* @param inherit {@code true} to inherit, {@code false} to not inherit
* @return this builder
*/
Builder inheritInheritableThreadLocals(boolean inherit);
/**
* Sets the uncaught exception handler.
* @param ueh uncaught exception handler
* @return this builder
*/
Builder uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
/**
* Creates a new {@code Thread} from the current state of the builder to
* run the given task. The {@code Thread}'s {@link Thread#start() start}
* method must be invoked to schedule the thread to execute.
*
* @param task the object to run when the thread executes
* @return a new unstarted Thread
* @throws SecurityException if denied by the security manager
* (See <a href="Thread.html#ofplatform-security">Interaction with
* security manager when creating platform threads</a>)
*
* @see <a href="Thread.html#inheritance">Inheritance when creating threads</a>
*/
Thread unstarted(Runnable task);
/**
* Creates a new {@code Thread} from the current state of the builder and
* schedules it to execute.
*
* @param task the object to run when the thread executes
* @return a new started Thread
* @throws SecurityException if denied by the security manager
* (See <a href="Thread.html#ofplatform-security">Interaction with
* security manager when creating platform threads</a>)
*
* @see <a href="Thread.html#inheritance">Inheritance when creating threads</a>
*/
Thread start(Runnable task);
/**
* Returns a {@code ThreadFactory} to create threads from the current
* state of the builder. The returned thread factory is safe for use by
* multiple concurrent threads.
*
* @return a thread factory to create threads
*/
ThreadFactory factory();
/**
* A builder for creating a platform {@link Thread} or {@link ThreadFactory}
* that creates platform threads.
*
* <p> Unless otherwise specified, passing a null argument to a method in
* this interface causes a {@code NullPointerException} to be thrown.
*
* @see Thread#ofPlatform()
* @since 19
*/
@PreviewFeature(feature = PreviewFeature.Feature.VIRTUAL_THREADS)
sealed interface OfPlatform extends Builder
permits ThreadBuilders.PlatformThreadBuilder {
@Override OfPlatform name(String name);
/**
* @throws IllegalArgumentException {@inheritDoc}
*/
@Override OfPlatform name(String prefix, long start);
@Override OfPlatform allowSetThreadLocals(boolean allow);
@Override OfPlatform inheritInheritableThreadLocals(boolean inherit);
@Override OfPlatform uncaughtExceptionHandler(UncaughtExceptionHandler ueh);
/**
* Sets the thread group.
* @param group the thread group
* @return this builder
*/
OfPlatform group(ThreadGroup group);
/**
* Sets the daemon status.
* @param on {@code true} to create daemon threads