-
Notifications
You must be signed in to change notification settings - Fork 720
/
Thread.java
1572 lines (1446 loc) · 49.8 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
/*[INCLUDE-IF (8 <= JAVA_SPEC_VERSION) & (JAVA_SPEC_VERSION < 19)]*/
/*
* Copyright IBM Corp. and others 1998
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] https://openjdk.org/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 OR GPL-2.0-only WITH OpenJDK-assembly-exception-1.0
*/
package java.lang;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.Map;
/*[IF Sidecar18-SE-OpenJ9]*/
import jdk.internal.misc.TerminatingThreadLocal;
/*[ENDIF] Sidecar18-SE-OpenJ9 */
/*[IF JAVA_SPEC_VERSION >= 11]*/
import java.util.Properties;
import jdk.internal.reflect.CallerSensitive;
/*[ELSE] JAVA_SPEC_VERSION >= 11 */
import sun.reflect.CallerSensitive;
/*[ENDIF] JAVA_SPEC_VERSION >= 11 */
import sun.nio.ch.Interruptible;
import sun.security.util.SecurityConstants;
/**
* A Thread is a unit of concurrent execution in Java. It has its own call stack
* for methods being called and their parameters. Threads in the same VM interact and
* synchronize by the use of shared Objects and monitors associated with these objects.
* Synchronized methods and part of the API in Object also allow Threads to cooperate.
*
* When a Java program starts executing there is an implicit Thread (called "main")
* which is automatically created by the VM. This Thread belongs to a ThreadGroup
* (also called "main") which is automatically created by the bootstrap sequence by
* the VM as well.
*
* @see java.lang.Object
* @see java.lang.ThreadGroup
*/
public class Thread implements Runnable {
/* Maintain thread shape in all configs */
/**
* The maximum priority value for a Thread.
*/
public final static int MAX_PRIORITY = 10; // Maximum allowed priority for a thread
/**
* The minimum priority value for a Thread.
*/
public final static int MIN_PRIORITY = 1; // Minimum allowed priority for a thread
/**
* The default priority value for a Thread.
*/
public final static int NORM_PRIORITY = 5; // Normal priority for a thread
/*[PR 97331] Initial thread name should be Thread-0 */
private static int createCount; // Used internally to compute Thread names that comply with the Java specification
/*[PR 122459] LIR646 - Remove use of generic object for synchronization */
private static final class TidLock {
TidLock() {}
}
private static Object tidLock = new TidLock();
private static long tidCount = 1;
private static final int NANOS_MAX = 999999; // Max value for nanoseconds parameter to sleep and join
private static final int INITIAL_LOCAL_STORAGE_CAPACITY = 5; // Initial number of local storages when the Thread is created
static final long NO_REF = 0; // Symbolic constant, no threadRef assigned or already cleaned up
// Instance variables
private volatile long threadRef; // Used by the VM
long stackSize = 0;
/*[IF JAVA_SPEC_VERSION >= 14]*/
/* deadInterrupt tracks the thread interrupt state when threadRef has no reference (ie thread is not alive).
* Note that this value need not be updated while the thread is running since the interrupt state will be
* tracked by the vm during that time. Because of this the value should not be used over calling
* isInterrupted() or interrupted().
*/
private volatile boolean deadInterrupt;
/*[ENDIF] JAVA_SPEC_VERSION >= 14 */
private volatile boolean started; // If !isAlive(), tells if Thread died already or hasn't even started
private String name; // The Thread's name
private int priority = NORM_PRIORITY; // The Thread's current priority
private boolean isDaemon; // Tells if the Thread is a daemon thread or not.
ThreadGroup group; // A Thread belongs to exactly one ThreadGroup
private Runnable runnable; // Target (optional) runnable object
private boolean stopCalled = false; // Used by the VM
/*[PR 1FENTZW]*/
private ClassLoader contextClassLoader; // Used to find classes and resources in this Thread
ThreadLocal.ThreadLocalMap threadLocals;
private AccessControlContext inheritedAccessControlContext;
/*[PR 96127]*/
/*[PR 122459] LIR646 - Remove use of generic object for synchronization */
private static final class ThreadLock {}
private Object lock = new ThreadLock();
ThreadLocal.ThreadLocalMap inheritableThreadLocals;
private volatile Interruptible blockOn;
int threadLocalsIndex;
int inheritableThreadLocalsIndex;
/*[PR 113602] Thread fields should be volatile */
private volatile UncaughtExceptionHandler exceptionHandler;
private long tid;
volatile Object parkBlocker;
private static ThreadGroup systemThreadGroup; // Assigned by the vm
private static ThreadGroup mainGroup; // ThreadGroup where the "main" Thread starts
/*[PR 113602] Thread fields should be volatile */
private volatile static UncaughtExceptionHandler defaultExceptionHandler;
/*[PR CMVC 196696] Build error:java.lang.Thread need extra fields */
long threadLocalRandomSeed;
int threadLocalRandomProbe;
int threadLocalRandomSecondarySeed;
private static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0];
/**
* Constructs a new Thread with no runnable object and a newly generated name.
* The new Thread will belong to the same ThreadGroup as the Thread calling
* this constructor.
*
* @see java.lang.ThreadGroup
*/
public Thread() {
this(null, null, newName(), null, true);
}
/**
*
* Private constructor to be used by the VM for the threads attached through JNI.
* They already have a running thread with no associated Java Thread, so this is
* where the binding is done.
*
* @param vmName Name for the Thread being created (or null to auto-generate a name)
* @param vmThreadGroup ThreadGroup for the Thread being created (or null for main threadGroup)
* @param vmPriority Priority for the Thread being created
* @param vmIsDaemon Indicates whether or not the Thread being created is a daemon thread
*
* @see java.lang.ThreadGroup
*/
private Thread(String vmName, Object vmThreadGroup, int vmPriority, boolean vmIsDaemon) {
super();
String threadName = (vmName == null) ? newName() : vmName;
/*[IF JAVA_SPEC_VERSION < 15]*/
setNameImpl(threadRef, threadName);
/*[ENDIF] JAVA_SPEC_VERSION < 15 */
name = threadName;
isDaemon = vmIsDaemon;
priority = vmPriority; // If we called setPriority(), it would have to be after setting the ThreadGroup (further down),
// because of the checkAccess() call (which requires the ThreadGroup set). However, for the main
// Thread or JNI-C attached Threads we just trust the value the VM is passing us, and just assign.
ThreadGroup threadGroup = null;
boolean booting = false;
if (mainGroup == null) { // only occurs during bootstrap
booting = true;
/*[PR CMVC 71192] Initialize the "main" thread group without calling checkAccess() */
mainGroup = new ThreadGroup(systemThreadGroup);
} else {
/*[IF JAVA_SPEC_VERSION >= 15]*/
setNameImpl(threadRef, threadName);
/*[ENDIF] JAVA_SPEC_VERSION >= 15 */
}
threadGroup = vmThreadGroup == null ? mainGroup : (ThreadGroup)vmThreadGroup;
/*[PR 1FEVFSU] The rest of the configuration/initialization is shared between this constructor and the public one */
initialize(booting, threadGroup, null, null, true); // no parent Thread
/*[PR 115667, CMVC 94448] In 1.5 and CDC/Foundation 1.1, thread is added to ThreadGroup when started */
this.group.add(this);
/*[PR 100718] Initialize System.in after the main thread */
if (booting) {
/*[IF JAVA_SPEC_VERSION >= 15]*/
/* JDK15+ native method binding uses java.lang.ClassLoader.findNative():bootstrapClassLoader.nativelibs.find(entryName)
* to lookup native address when not found within systemClassLoader native libraries.
* This requires bootstrapClassLoader is initialized via initialize(booting, threadGroup, null, null, true) above before
* invoking a native method not present within systemClassLoader native libraries such as following setNameImpl modified
* via JVMTI agent SetNativeMethodPrefix (https://github.com/eclipse-openj9/openj9/issues/11181).
* After bootstrapClassLoader initialization, setNameImpl can be invoked before initialize() to set thread name earlier.
*/
setNameImpl(threadRef, threadName);
/*[ENDIF] JAVA_SPEC_VERSION >= 15 */
System.completeInitialization();
}
}
/**
* Constructs a new Thread with a runnable object and a newly generated name.
* The new Thread will belong to the same ThreadGroup as the Thread calling
* this constructor.
*
* @param runnable a java.lang.Runnable whose method <code>run</code> will be executed by the new Thread
*
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
*/
public Thread(Runnable runnable) {
this(null, runnable, newName(), null, true);
}
/*
* [PR CMVC 199693] Prevent a trusted method chain attack.
*/
/**
* Constructs a new Thread with a runnable object and a newly generated name,
* setting the specified AccessControlContext.
* The new Thread will belong to the same ThreadGroup as the Thread calling
* this constructor.
*
* @param runnable a java.lang.Runnable whose method <code>run</code> will be executed by the new Thread
* @param acc the AccessControlContext to use for the Thread
*
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
*/
Thread(Runnable runnable, AccessControlContext acc) {
this(null, runnable, newName(), acc, false);
}
/**
* Constructs a new Thread with a runnable object and name provided.
* The new Thread will belong to the same ThreadGroup as the Thread calling
* this constructor.
*
* @param runnable a java.lang.Runnable whose method <code>run</code> will be executed by the new Thread
* @param threadName Name for the Thread being created
*
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
*/
public Thread(Runnable runnable, String threadName) {
this(null, runnable, threadName, null, true);
}
/**
* Constructs a new Thread with no runnable object and the name provided.
* The new Thread will belong to the same ThreadGroup as the Thread calling
* this constructor.
*
* @param threadName Name for the Thread being created
*
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
*/
public Thread(String threadName) {
this(null, null, threadName, null, true);
}
/**
* Constructs a new Thread with a runnable object and a newly generated name.
* The new Thread will belong to the ThreadGroup passed as parameter.
*
* @param group ThreadGroup to which the new Thread will belong
* @param runnable a java.lang.Runnable whose method <code>run</code> will be executed by the new Thread
*
* @exception SecurityException
* if <code>group.checkAccess()</code> fails with a SecurityException
* @exception IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
*
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
* @see java.lang.SecurityException
* @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, Runnable runnable) {
this(group, runnable, newName(), null, true);
}
/**
* Constructs a new Thread with a runnable object, the given name and
* belonging to the ThreadGroup passed as parameter.
*
* @param group ThreadGroup to which the new Thread will belong
* @param runnable a java.lang.Runnable whose method <code>run</code> will be executed by the new Thread
* @param threadName Name for the Thread being created
* @param stack Platform dependent stack size
*
* @exception SecurityException
* if <code>group.checkAccess()</code> fails with a SecurityException
* @exception IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
*
* @since 1.4
*
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
* @see java.lang.SecurityException
* @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, Runnable runnable, String threadName, long stack) {
this(group, runnable, threadName, null, true);
this.stackSize = stack;
}
/*[IF JAVA_SPEC_VERSION >= 9]*/
/**
* Constructs a new Thread with a runnable object, the given name, the thread stack size,
* the flag to inherit initial values for inheritable thread-local variables and
* belonging to the ThreadGroup passed as parameter.
*
* @param group ThreadGroup to which the new Thread will belong
* @param runnable A java.lang.Runnable whose method <code>run</code> will be executed by the new Thread
* @param threadName Name for the Thread being created
* @param stack Platform dependent stack size
* @param inheritThreadLocals A boolean indicating whether to inherit initial values for inheritable thread-local variables.
*
* @exception SecurityException
* if <code>group.checkAccess()</code> fails with a SecurityException
* @exception IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
*
*/
public Thread(ThreadGroup group, Runnable runnable, String threadName, long stack, boolean inheritThreadLocals) {
this(group, runnable, threadName, null, inheritThreadLocals);
this.stackSize = stack;
}
/*[ENDIF] JAVA_SPEC_VERSION >= 9 */
/**
* Constructs a new Thread with a runnable object, the given name and
* belonging to the ThreadGroup passed as parameter.
*
* @param group ThreadGroup to which the new Thread will belong
* @param runnable a java.lang.Runnable whose method <code>run</code> will be executed by the new Thread
* @param threadName Name for the Thread being created
*
* @exception SecurityException
* if <code>group.checkAccess()</code> fails with a SecurityException
* @exception IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
*
* @see java.lang.ThreadGroup
* @see java.lang.Runnable
* @see java.lang.SecurityException
* @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, Runnable runnable, String threadName) {
this(group, runnable, threadName, null, true);
}
Thread(Runnable runnable, String threadName, boolean isSystemThreadGroup, boolean inheritThreadLocals, boolean isDaemon, ClassLoader contextClassLoader) {
this(isSystemThreadGroup ? systemThreadGroup : null, runnable, threadName, null, inheritThreadLocals);
this.isDaemon = isDaemon;
this.contextClassLoader = contextClassLoader;
}
private Thread(ThreadGroup group, Runnable runnable, String threadName, AccessControlContext acc, boolean inheritThreadLocals) {
super();
/*[PR 1FEVFSU] Re-arrange method so that common code to this constructor and the private one the VM calls can be put in a separate method */
/*[PR 1FIGT59] name cannot be null*/
if (threadName==null) throw new NullPointerException();
this.name = threadName; // We avoid the public API 'setName', since it does redundant work (checkAccess)
this.runnable = runnable; // No API available here, so just direct access to inst. var.
Thread currentThread = currentThread();
this.isDaemon = currentThread.isDaemon(); // We avoid the public API 'setDaemon', since it does redundant work (checkAccess)
/*[PR 1FEO92F] (dup of 1FC0TRN) */
if (group == null) {
@SuppressWarnings("removal")
SecurityManager currentManager = System.getSecurityManager();
// if there is a security manager...
if (currentManager != null)
// Ask SecurityManager for ThreadGroup
group = currentManager.getThreadGroup();
}
/*[PR 94235]*/
if (group == null)
// Same group as Thread that created us
group = currentThread.getThreadGroup();
/*[PR 1FEVFSU] The rest of the configuration/initialization is shared between this constructor and the private one */
initialize(false, group, currentThread, acc, inheritThreadLocals);
setPriority(currentThread.getPriority()); // In this case we can call the public API according to the spec - 20.20.10
}
/**
* Initialize the thread according to its parent Thread and the ThreadGroup
* where it should be added.
*
* @param booting Indicates if the JVM is booting up, i.e. if the main thread is being attached
* @param threadGroup ThreadGroup The ThreadGroup to which the receiver is being added.
* @param parentThread Thread The creator Thread from which to inherit some values like local storage, etc.
* If null, the receiver is either the main Thread or a JNI-C attached Thread.
* @param acc The AccessControlContext. If null, use the current context
* @param inheritThreadLocals A boolean indicating whether to inherit initial values for inheritable thread-local variables.
*/
private void initialize(boolean booting, ThreadGroup threadGroup, Thread parentThread, AccessControlContext acc, boolean inheritThreadLocals) {
synchronized (tidLock) {
tid = tidCount++;
}
/*[PR 96408]*/
this.group = threadGroup;
if (booting) {
System.afterClinitInitialization();
}
// initialize the thread local storage before making other calls
if (parentThread != null) { // Non-main thread
if (inheritThreadLocals && (null != parentThread.inheritableThreadLocals)) {
inheritableThreadLocals = ThreadLocal.createInheritedMap(parentThread.inheritableThreadLocals);
}
/*[PR CMVC 90230] enableContextClassLoaderOverride check added in 1.5 */
@SuppressWarnings("removal")
final SecurityManager sm = System.getSecurityManager();
final Class<?> implClass = getClass();
final Class<?> thisClass = Thread.class;
if ((sm != null) && (implClass != thisClass)) {
boolean override = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
try {
Method method = implClass.getMethod("getContextClassLoader"); //$NON-NLS-1$
if (method.getDeclaringClass() != thisClass) {
return Boolean.TRUE;
}
} catch (NoSuchMethodException e) {
}
try {
Method method = implClass.getDeclaredMethod("setContextClassLoader", ClassLoader.class); //$NON-NLS-1$
if (method.getDeclaringClass() != thisClass) {
return Boolean.TRUE;
}
} catch (NoSuchMethodException e) {
}
return Boolean.FALSE;
}
}).booleanValue();
if (override) {
sm.checkPermission(com.ibm.oti.util.RuntimePermissions.permissionEnableContextClassLoaderOverride);
}
}
// By default a Thread "inherits" the context ClassLoader from its creator
/*[PR CMVC 90230] behavior change in 1.5, call getContextClassLoader() instead of accessing field */
contextClassLoader = parentThread.getContextClassLoader();
} else { // no parent: main thread, or one attached through JNI-C
/*[PR 111189] Do not initialize ClassLoaders in a static initializer */
if (booting) {
// Preload and initialize the JITHelpers class
try {
Class.forName("com.ibm.jit.JITHelpers"); //$NON-NLS-1$
} catch(ClassNotFoundException e) {
// Continue silently if the class can't be loaded and initialized for some reason,
// The JIT will tolerate this.
}
// Explicitly initialize ClassLoaders, so ClassLoader methods (such as
// ClassLoader.callerClassLoader) can be used before System is initialized
ClassLoader.initializeClassLoaders();
}
// Just set the context class loader
contextClassLoader = ClassLoader.getSystemClassLoader();
}
threadGroup.checkAccess();
/*[PR 115667, CMVC 94448] In 1.5 and CDC/Foundation 1.1, thread is added to ThreadGroup when started */
threadGroup.checkNewThread(this);
inheritedAccessControlContext = acc == null ? AccessController.getContext() : acc;
}
/**
* Constructs a new Thread with no runnable object, the given name and
* belonging to the ThreadGroup passed as parameter.
*
* @param group ThreadGroup to which the new Thread will belong
* @param threadName Name for the Thread being created
*
* @exception SecurityException
* if <code>group.checkAccess()</code> fails with a SecurityException
* @exception IllegalThreadStateException
* if <code>group.destroy()</code> has already been done
*
* @see java.lang.ThreadGroup
* @see java.lang.SecurityException
* @see java.lang.SecurityManager
*/
public Thread(ThreadGroup group, String threadName) {
this(group, null, threadName, null, true);
}
/**
* Returns how many threads are active in the <code>ThreadGroup</code>
* which the current thread belongs to.
*
* @return Number of Threads
*/
public static int activeCount(){
/*[PR CMVC 93001] changed in 1.5 to only count active threads */
return currentThread().getThreadGroup().activeCount();
}
/**
* This method is used for operations that require approval from
* a SecurityManager. If there's none installed, this method is a no-op.
* If there's a SecurityManager installed , <code>checkAccess(Ljava.lang.Thread;)</code>
* is called for that SecurityManager.
*
* @see java.lang.SecurityException
* @see java.lang.SecurityManager
*/
/*[IF JAVA_SPEC_VERSION >= 17]*/
@Deprecated(since="17", forRemoval=true)
/*[ENDIF] JAVA_SPEC_VERSION >= 17 */
public final void checkAccess() {
@SuppressWarnings("removal")
SecurityManager currentManager = System.getSecurityManager();
if (currentManager != null) currentManager.checkAccess(this);
}
/**
* Returns the number of stack frames in this thread.
*
* @return Number of stack frames
*
/*[IF JAVA_SPEC_VERSION >= 14]
* @exception UnsupportedOperationException
/*[ENDIF] JAVA_SPEC_VERSION >= 14
*
* @deprecated The semantics of this method are poorly defined and it uses the deprecated suspend() method.
*/
/*[IF JAVA_SPEC_VERSION >= 11]*/
@Deprecated(forRemoval=true, since="1.2")
/*[ELSE] JAVA_SPEC_VERSION >= 11 */
@Deprecated
/*[ENDIF] JAVA_SPEC_VERSION >= 11 */
public int countStackFrames() {
/*[IF JAVA_SPEC_VERSION >= 14]*/
throw new UnsupportedOperationException();
/*[ELSE] JAVA_SPEC_VERSION >= 14 */
return 0;
/*[ENDIF] JAVA_SPEC_VERSION >= 14 */
}
/**
* Answers the instance of Thread that corresponds to the running Thread
* which calls this method.
*
* @return a java.lang.Thread corresponding to the code that called <code>currentThread()</code>
*/
public static native Thread currentThread();
/*[IF JAVA_SPEC_VERSION < 11]*/
/**
* Destroys the receiver without any monitor cleanup. Not implemented.
*
* @deprecated May cause deadlocks.
*/
/*[IF JAVA_SPEC_VERSION >= 9]*/
@Deprecated(forRemoval=true, since="1.5")
/*[ELSE] JAVA_SPEC_VERSION >= 9 */
@Deprecated
/*[ENDIF] JAVA_SPEC_VERSION >= 9 */
public void destroy() {
/*[PR 121318] Should throw NoSuchMethodError */
throw new NoSuchMethodError();
}
/*[ENDIF] JAVA_SPEC_VERSION < 11 */
/**
* Prints a text representation of the stack for this Thread.
*/
public static void dumpStack() {
new Throwable().printStackTrace();
}
/**
* Copies an array with all Threads which are in the same ThreadGroup as
* the receiver - and subgroups - into the array <code>threads</code>
* passed as parameter. If the array passed as parameter is too small no
* exception is thrown - the extra elements are simply not copied.
*
* @param threads array into which the Threads will be copied
*
* @return How many Threads were copied over
*
* @exception SecurityException
* if the installed SecurityManager fails <code>checkAccess(Ljava.lang.Thread;)</code>
*
* @see java.lang.SecurityException
* @see java.lang.SecurityManager
*/
public static int enumerate(Thread[] threads) {
return currentThread().getThreadGroup().enumerate(threads, true);
}
/**
* Returns the context ClassLoader for the receiver.
*
* @return ClassLoader The context ClassLoader
*
* @see java.lang.ClassLoader
* @see #getContextClassLoader()
*/
@CallerSensitive
public ClassLoader getContextClassLoader() {
/*[PR 1FCA807]*/
/*[PR 1FDTAMT] use callerClassLoader()*/
if (contextClassLoader == null) {
return null;
}
@SuppressWarnings("removal")
SecurityManager currentManager = System.getSecurityManager();
// if there is a security manager...
if (currentManager != null) {
ClassLoader callerClassLoader = ClassLoader.callerClassLoader();
if (ClassLoader.needsClassLoaderPermissionCheck(callerClassLoader, contextClassLoader)) {
currentManager.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
return contextClassLoader;
}
/**
* Answers the name of the receiver.
*
* @return the receiver's name (a java.lang.String)
*/
public final String getName() {
return name;
}
/**
* Answers the priority of the receiver.
*
* @return the receiver's priority (an <code>int</code>)
*
* @see Thread#setPriority
*/
public final int getPriority() {
return priority;
}
/**
* Answers the ThreadGroup to which the receiver belongs
*
* @return the receiver's ThreadGroup
*/
public final ThreadGroup getThreadGroup() {
return group;
}
/**
* Posts an interrupt request to the receiver
*
/*[IF JAVA_SPEC_VERSION >= 14]
* From Java 14, the interrupt state for threads that are not alive is tracked.
/*[ENDIF] JAVA_SPEC_VERSION >= 14
*
* @exception SecurityException
* if <code>group.checkAccess()</code> fails with a SecurityException
*
* @see java.lang.SecurityException
* @see java.lang.SecurityManager
* @see Thread#interrupted
* @see Thread#isInterrupted
*/
public void interrupt() {
@SuppressWarnings("removal")
SecurityManager currentManager = System.getSecurityManager();
if (currentManager != null) {
if (currentThread() != this) {
currentManager.checkAccess(this);
}
}
synchronized (lock) {
interruptImpl();
Interruptible localBlockOn = blockOn;
if (localBlockOn != null) {
localBlockOn.interrupt(this);
}
}
}
/**
* Answers a <code>boolean</code> indicating whether the current Thread
* (<code>currentThread()</code>) has a pending interrupt request
* (<code>true</code>) or not (<code>false</code>). It also has the
* side-effect of clearing the flag.
*
* @return a <code>boolean</code>
*
* @see Thread#currentThread
* @see Thread#interrupt
* @see Thread#isInterrupted
*/
public static boolean interrupted() {
return interruptedImpl();
}
private static native boolean interruptedImpl();
/**
* Posts an interrupt request to the receiver
*
/*[IF JAVA_SPEC_VERSION >= 14]
* From Java 14, the interrupt state for threads that are not alive is tracked.
/*[ENDIF] JAVA_SPEC_VERSION >= 14
*
* @see Thread#interrupted
* @see Thread#isInterrupted
*/
private native void interruptImpl();
/**
* Answers <code>true</code> if the receiver has
* already been started and still runs code (hasn't died yet).
* Answers <code>false</code> either if the receiver hasn't been
* started yet or if it has already started and run to completion and died.
*
* @return a <code>boolean</code>
*
* @see Thread#start
*/
public final boolean isAlive() {
/*[PR CMVC 88976] the Thread is alive until cleanup() is called */
return threadRef != NO_REF;
}
/**
* Answers <code>true</code> if the receiver has
* already died and been removed from the ThreadGroup
* where it belonged.
*
* @return a <code>boolean</code>
*
* @see Thread#start
* @see Thread#isAlive
*/
private boolean isDead() {
/* Has already started and is not alive anymore. */
return (started && (threadRef == NO_REF));
}
/**
* Answers a <code>boolean</code> indicating whether the receiver
* is a daemon Thread (<code>true</code>) or not (<code>false</code>)
* A daemon Thread only runs as long as there are non-daemon Threads
* running. When the last non-daemon Thread ends, the whole program ends
* no matter if it had daemon Threads still running or not.
*
* @return a <code>boolean</code>
*
* @see Thread#setDaemon
*/
public final boolean isDaemon() {
return this.isDaemon;
}
/**
* Answers a <code>boolean</code> indicating whether the receiver
* has a pending interrupt request (<code>true</code>) or not (<code>false</code>)
*
* @return a <code>boolean</code>
*
* @see Thread#interrupt
* @see Thread#interrupted
*/
public boolean isInterrupted() {
synchronized(lock) {
return isInterruptedImpl();
}
}
private native boolean isInterruptedImpl();
/**
* Blocks the current Thread (<code>Thread.currentThread()</code>) until the
* receiver finishes its execution and dies.
*
* @exception InterruptedException
* if <code>interrupt()</code> was called for the receiver while
* it was in the <code>join()</code> call
*
* @see Object#notifyAll
* @see java.lang.ThreadDeath
*/
public final synchronized void join() throws InterruptedException {
join(0, 0);
}
/**
* Blocks the current Thread (<code>Thread.currentThread()</code>) until the
* receiver finishes its execution and dies or the specified timeout expires, whatever
* happens first.
*
* @param timeoutInMilliseconds The maximum time to wait (in milliseconds).
*
* @exception InterruptedException
* if <code>interrupt()</code> was called for the receiver while
* it was in the <code>join()</code> call
*
* @see Object#notifyAll
* @see java.lang.ThreadDeath
*/
public final void join(long timeoutInMilliseconds) throws InterruptedException {
join(timeoutInMilliseconds, 0);
}
/**
* Blocks the current Thread (<code>Thread.currentThread()</code>) until the
* receiver finishes its execution and dies or the specified timeout expires, whatever
* happens first.
*
* @param timeoutInMilliseconds The maximum time to wait (in milliseconds).
* @param nanos Extra nanosecond precision
*
* @exception InterruptedException
* if <code>interrupt()</code> was called for the receiver while
* it was in the <code>join()</code> call
*
* @see Object#notifyAll
* @see java.lang.ThreadDeath
*/
public final synchronized void join(long timeoutInMilliseconds, int nanos) throws InterruptedException {
if ((timeoutInMilliseconds < 0) || (nanos < 0) || (nanos > NANOS_MAX)) {
throw new IllegalArgumentException();
}
if (!started || isDead()) {
return;
}
if ((timeoutInMilliseconds == 0) && (nanos == 0)) {
while (!isDead()) {
wait(0);
}
return;
}
long toWaitNano = TimeUnit.MILLISECONDS.toNanos(timeoutInMilliseconds);
if ((Long.MAX_VALUE - toWaitNano) >= nanos) {
toWaitNano += nanos;
} else {
// Unlikely just for technical correctness.
toWaitNano = Long.MAX_VALUE;
}
/*[PR 1FJMO7Q] A Thread can be !isAlive() and still be in its ThreadGroup. Use isDead() */
while (!isDead()) {
final long start = System.nanoTime();
TimeUnit.NANOSECONDS.timedWait(this, toWaitNano);
final long waited = System.nanoTime() - start;
// Anyone could do a synchronized/notify on this thread, so if we wait
// less than the timeout, we must check if the thread really died
if (waited >= toWaitNano) {
break;
} else {
toWaitNano -= waited;
}
}
}
/**
* Private method that generates Thread names that comply with the Java specification
*
* @version initial
*
* @return a java.lang.String representing a name for the next Thread being generated
*
* @see Thread#createCount
*/
private synchronized static String newName() {
/*[PR 97331] Initial thread name should be Thread-0 */
return "Thread-" + createCount++; //$NON-NLS-1$
}
/**
* This is a no-op if the receiver was never suspended, or suspended and already
* resumed. If the receiver is suspended, however, makes it resume to the point
* where it was when it was suspended.
*
* @exception SecurityException
* if <code>checkAccess()</code> fails with a SecurityException
*
* @see Thread#suspend()
*
* @deprecated Used with deprecated method Thread.suspend().
*/
/*[IF JAVA_SPEC_VERSION >= 11]*/
/*[IF JAVA_SPEC_VERSION >= 14]*/
@Deprecated(forRemoval=true, since="1.2")
/*[ELSE] JAVA_SPEC_VERSION >= 14 */
@Deprecated(forRemoval=false, since="1.2")
/*[ENDIF] JAVA_SPEC_VERSION >= 14 */
/*[ELSE] JAVA_SPEC_VERSION >= 11 */
@Deprecated
/*[ENDIF] JAVA_SPEC_VERSION >= 11 */
public final void resume() {
checkAccess();
synchronized(lock) {
resumeImpl();
}
}
/**
* Private method for the VM to do the actual work of resuming the Thread
*
*/
private native void resumeImpl();
/**
* Calls the <code>run()</code> method of the Runnable object the receiver holds.
* If no Runnable is set, does nothing.
*
* @see Thread#start
*/
public void run() {
if (runnable != null) {
runnable.run();
}
}
/**
* Set the context ClassLoader for the receiver.
*
* @param cl The context ClassLoader
*
* @see java.lang.ClassLoader
* @see #getContextClassLoader()
*/
public void setContextClassLoader(ClassLoader cl) {
/*[PR 1FCA807]*/
@SuppressWarnings("removal")
SecurityManager currentManager = System.getSecurityManager();
// if there is a security manager...
if (currentManager != null) {
// then check permission
currentManager.checkPermission(com.ibm.oti.util.RuntimePermissions.permissionSetContextClassLoader);
}
contextClassLoader = cl;
}
void internalSetContextClassLoader(ClassLoader cl) {
contextClassLoader = cl;
}
/**
* Set if the receiver is a daemon Thread or not. This can only be done
* before the Thread starts running.
*
* @param isDaemon A boolean indicating if the Thread should be daemon or not
*
* @exception SecurityException
* if <code>checkAccess()</code> fails with a SecurityException
*
* @see Thread#isDaemon
*/
public final void setDaemon(boolean isDaemon) {
checkAccess();
synchronized(lock) {
if (!this.started) {
this.isDaemon = isDaemon;
} else {
/*[PR CVMC 82531] Only throw IllegalThreadStateException if the thread is alive */
if (isAlive()) {
throw new IllegalThreadStateException();
}
}
}
}
/**
* Sets the name of the receiver.
*
* @param threadName new name for the Thread
*
* @exception SecurityException
* if <code>checkAccess()</code> fails with a SecurityException
*