-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathjavaThread.cpp
2297 lines (1992 loc) · 80.3 KB
/
javaThread.cpp
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) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, Azul Systems, Inc. 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.
*
* 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.
*
*/
#include "precompiled.hpp"
#include "cds/dynamicArchive.hpp"
#include "ci/ciEnv.hpp"
#include "classfile/javaClasses.inline.hpp"
#include "classfile/javaThreadStatus.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmClasses.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/codeCache.hpp"
#include "code/scopeDesc.hpp"
#include "compiler/compileTask.hpp"
#include "compiler/compilerThread.hpp"
#include "gc/shared/oopStorage.hpp"
#include "gc/shared/oopStorageSet.hpp"
#include "gc/shared/tlab_globals.hpp"
#include "jfr/jfrEvents.hpp"
#include "jvm.h"
#include "jvmtifiles/jvmtiEnv.hpp"
#include "logging/log.hpp"
#include "logging/logAsyncWriter.hpp"
#include "logging/logStream.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/iterator.hpp"
#include "memory/universe.hpp"
#include "oops/access.inline.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/klass.inline.hpp"
#include "oops/oop.inline.hpp"
#include "oops/oopHandle.inline.hpp"
#include "oops/verifyOopClosure.hpp"
#include "prims/jvm_misc.hpp"
#include "prims/jvmtiDeferredUpdates.hpp"
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiThreadState.inline.hpp"
#include "runtime/atomic.hpp"
#include "runtime/continuation.hpp"
#include "runtime/continuationEntry.inline.hpp"
#include "runtime/continuationHelper.inline.hpp"
#include "runtime/deoptimization.hpp"
#include "runtime/frame.inline.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/handshake.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/javaThread.inline.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/lockStack.inline.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/orderAccess.hpp"
#include "runtime/os.inline.hpp"
#include "runtime/osThread.hpp"
#include "runtime/safepoint.hpp"
#include "runtime/safepointMechanism.inline.hpp"
#include "runtime/safepointVerifiers.hpp"
#include "runtime/serviceThread.hpp"
#include "runtime/stackFrameStream.inline.hpp"
#include "runtime/stackWatermarkSet.hpp"
#include "runtime/synchronizer.hpp"
#include "runtime/threadCritical.hpp"
#include "runtime/threadSMR.inline.hpp"
#include "runtime/threadStatisticalInfo.hpp"
#include "runtime/threadWXSetters.inline.hpp"
#include "runtime/timer.hpp"
#include "runtime/timerTrace.hpp"
#include "runtime/vframe.inline.hpp"
#include "runtime/vframeArray.hpp"
#include "runtime/vframe_hp.hpp"
#include "runtime/vmThread.hpp"
#include "runtime/vmOperations.hpp"
#include "services/threadService.hpp"
#include "utilities/copy.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/macros.hpp"
#include "utilities/preserveException.hpp"
#include "utilities/spinYield.hpp"
#include "utilities/vmError.hpp"
#if INCLUDE_JVMCI
#include "jvmci/jvmci.hpp"
#include "jvmci/jvmciEnv.hpp"
#endif
#if INCLUDE_JFR
#include "jfr/jfr.hpp"
#endif
// Set by os layer.
size_t JavaThread::_stack_size_at_create = 0;
#ifdef DTRACE_ENABLED
// Only bother with this argument setup if dtrace is available
#define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
#define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
#define DTRACE_THREAD_PROBE(probe, javathread) \
{ \
ResourceMark rm(this); \
int len = 0; \
const char* name = (javathread)->name(); \
len = strlen(name); \
HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \
(char *) name, len, \
java_lang_Thread::thread_id((javathread)->threadObj()), \
(uintptr_t) (javathread)->osthread()->thread_id(), \
java_lang_Thread::is_daemon((javathread)->threadObj())); \
}
#else // ndef DTRACE_ENABLED
#define DTRACE_THREAD_PROBE(probe, javathread)
#endif // ndef DTRACE_ENABLED
void JavaThread::smr_delete() {
if (_on_thread_list) {
ThreadsSMRSupport::smr_delete(this);
} else {
delete this;
}
}
// Initialized by VMThread at vm_global_init
OopStorage* JavaThread::_thread_oop_storage = nullptr;
OopStorage* JavaThread::thread_oop_storage() {
assert(_thread_oop_storage != nullptr, "not yet initialized");
return _thread_oop_storage;
}
void JavaThread::set_threadOopHandles(oop p) {
assert(_thread_oop_storage != nullptr, "not yet initialized");
_threadObj = OopHandle(_thread_oop_storage, p);
_vthread = OopHandle(_thread_oop_storage, p);
_jvmti_vthread = OopHandle(_thread_oop_storage, p->is_a(vmClasses::BoundVirtualThread_klass()) ? p : nullptr);
_scopedValueCache = OopHandle(_thread_oop_storage, nullptr);
}
oop JavaThread::threadObj() const {
// Ideally we would verify the current thread is oop_safe when this is called, but as we can
// be called from a signal handler we would have to use Thread::current_or_null_safe(). That
// has overhead and also interacts poorly with GetLastError on Windows due to the use of TLS.
// Instead callers must verify oop safe access.
return _threadObj.resolve();
}
oop JavaThread::vthread() const {
return _vthread.resolve();
}
void JavaThread::set_vthread(oop p) {
assert(_thread_oop_storage != nullptr, "not yet initialized");
_vthread.replace(p);
}
oop JavaThread::jvmti_vthread() const {
return _jvmti_vthread.resolve();
}
void JavaThread::set_jvmti_vthread(oop p) {
assert(_thread_oop_storage != nullptr, "not yet initialized");
_jvmti_vthread.replace(p);
}
// If there is a virtual thread mounted then return vthread() oop.
// Otherwise, return threadObj().
oop JavaThread::vthread_or_thread() const {
oop result = vthread();
if (result == nullptr) {
result = threadObj();
}
return result;
}
oop JavaThread::scopedValueCache() const {
return _scopedValueCache.resolve();
}
void JavaThread::set_scopedValueCache(oop p) {
if (!_scopedValueCache.is_empty()) { // i.e. if the OopHandle has been allocated
_scopedValueCache.replace(p);
} else {
assert(p == nullptr, "not yet initialized");
}
}
void JavaThread::clear_scopedValueBindings() {
set_scopedValueCache(nullptr);
oop vthread_oop = vthread();
// vthread may be null here if we get a VM error during startup,
// before the java.lang.Thread instance has been created.
if (vthread_oop != nullptr) {
java_lang_Thread::clear_scopedValueBindings(vthread_oop);
}
}
void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
bool daemon, TRAPS) {
assert(thread_group.not_null(), "thread group should be specified");
assert(threadObj() == nullptr, "should only create Java thread object once");
InstanceKlass* ik = vmClasses::Thread_klass();
assert(ik->is_initialized(), "must be");
instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
// We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
// We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
// constructor calls Thread.current(), which must be set here.
java_lang_Thread::set_thread(thread_oop(), this);
set_threadOopHandles(thread_oop());
JavaValue result(T_VOID);
if (thread_name != nullptr) {
Handle name = java_lang_String::create_from_str(thread_name, CHECK);
// Thread gets assigned specified name and null target
JavaCalls::call_special(&result,
thread_oop,
ik,
vmSymbols::object_initializer_name(),
vmSymbols::threadgroup_string_void_signature(),
thread_group,
name,
CHECK);
} else {
// Thread gets assigned name "Thread-nnn" and null target
// (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
JavaCalls::call_special(&result,
thread_oop,
ik,
vmSymbols::object_initializer_name(),
vmSymbols::threadgroup_runnable_void_signature(),
thread_group,
Handle(),
CHECK);
}
os::set_priority(this, NormPriority);
if (daemon) {
java_lang_Thread::set_daemon(thread_oop());
}
}
// ======= JavaThread ========
#if INCLUDE_JVMCI
jlong* JavaThread::_jvmci_old_thread_counters;
static bool jvmci_counters_include(JavaThread* thread) {
return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
}
void JavaThread::collect_counters(jlong* array, int length) {
assert(length == JVMCICounterSize, "wrong value");
for (int i = 0; i < length; i++) {
array[i] = _jvmci_old_thread_counters[i];
}
for (JavaThread* tp : ThreadsListHandle()) {
if (jvmci_counters_include(tp)) {
for (int i = 0; i < length; i++) {
array[i] += tp->_jvmci_counters[i];
}
}
}
}
// Attempt to enlarge the array for per thread counters.
static jlong* resize_counters_array(jlong* old_counters, int current_size, int new_size) {
jlong* new_counters = NEW_C_HEAP_ARRAY_RETURN_NULL(jlong, new_size, mtJVMCI);
if (new_counters == nullptr) {
return nullptr;
}
if (old_counters == nullptr) {
old_counters = new_counters;
memset(old_counters, 0, sizeof(jlong) * new_size);
} else {
for (int i = 0; i < MIN2((int) current_size, new_size); i++) {
new_counters[i] = old_counters[i];
}
if (new_size > current_size) {
memset(new_counters + current_size, 0, sizeof(jlong) * (new_size - current_size));
}
FREE_C_HEAP_ARRAY(jlong, old_counters);
}
return new_counters;
}
// Attempt to enlarge the array for per thread counters.
bool JavaThread::resize_counters(int current_size, int new_size) {
jlong* new_counters = resize_counters_array(_jvmci_counters, current_size, new_size);
if (new_counters == nullptr) {
return false;
} else {
_jvmci_counters = new_counters;
return true;
}
}
class VM_JVMCIResizeCounters : public VM_Operation {
private:
int _new_size;
bool _failed;
public:
VM_JVMCIResizeCounters(int new_size) : _new_size(new_size), _failed(false) { }
VMOp_Type type() const { return VMOp_JVMCIResizeCounters; }
bool allow_nested_vm_operations() const { return true; }
void doit() {
// Resize the old thread counters array
jlong* new_counters = resize_counters_array(JavaThread::_jvmci_old_thread_counters, JVMCICounterSize, _new_size);
if (new_counters == nullptr) {
_failed = true;
return;
} else {
JavaThread::_jvmci_old_thread_counters = new_counters;
}
// Now resize each threads array
for (JavaThread* tp : ThreadsListHandle()) {
if (!tp->resize_counters(JVMCICounterSize, _new_size)) {
_failed = true;
break;
}
}
if (!_failed) {
JVMCICounterSize = _new_size;
}
}
bool failed() { return _failed; }
};
bool JavaThread::resize_all_jvmci_counters(int new_size) {
VM_JVMCIResizeCounters op(new_size);
VMThread::execute(&op);
return !op.failed();
}
#endif // INCLUDE_JVMCI
#ifdef ASSERT
// Checks safepoint allowed and clears unhandled oops at potential safepoints.
void JavaThread::check_possible_safepoint() {
if (_no_safepoint_count > 0) {
print_owned_locks();
assert(false, "Possible safepoint reached by thread that does not allow it");
}
#ifdef CHECK_UNHANDLED_OOPS
// Clear unhandled oops in JavaThreads so we get a crash right away.
clear_unhandled_oops();
#endif // CHECK_UNHANDLED_OOPS
// Macos/aarch64 should be in the right state for safepoint (e.g.
// deoptimization needs WXWrite). Crashes caused by the wrong state rarely
// happens in practice, making such issues hard to find and reproduce.
#if defined(__APPLE__) && defined(AARCH64)
if (AssertWXAtThreadSync) {
assert_wx_state(WXWrite);
}
#endif
}
void JavaThread::check_for_valid_safepoint_state() {
// Don't complain if running a debugging command.
if (DebuggingContext::is_enabled()) return;
// Check NoSafepointVerifier, which is implied by locks taken that can be
// shared with the VM thread. This makes sure that no locks with allow_vm_block
// are held.
check_possible_safepoint();
if (thread_state() != _thread_in_vm) {
fatal("LEAF method calling lock?");
}
if (GCALotAtAllSafepoints) {
// We could enter a safepoint here and thus have a gc
InterfaceSupport::check_gc_alot();
}
}
#endif // ASSERT
// A JavaThread is a normal Java thread
JavaThread::JavaThread(MemTag mem_tag) :
Thread(mem_tag),
// Initialize fields
_on_thread_list(false),
DEBUG_ONLY(_java_call_counter(0) COMMA)
_entry_point(nullptr),
_deopt_mark(nullptr),
_deopt_nmethod(nullptr),
_vframe_array_head(nullptr),
_vframe_array_last(nullptr),
_jvmti_deferred_updates(nullptr),
_callee_target(nullptr),
_vm_result(nullptr),
_vm_result_2(nullptr),
_current_pending_monitor(nullptr),
_current_pending_monitor_is_from_java(true),
_current_waiting_monitor(nullptr),
_active_handles(nullptr),
_free_handle_block(nullptr),
_suspend_flags(0),
_thread_state(_thread_new),
_saved_exception_pc(nullptr),
#ifdef ASSERT
_no_safepoint_count(0),
_visited_for_critical_count(false),
#endif
_terminated(_not_terminated),
_in_deopt_handler(0),
_doing_unsafe_access(false),
_do_not_unlock_if_synchronized(false),
#if INCLUDE_JVMTI
_carrier_thread_suspended(false),
_is_in_VTMS_transition(false),
_is_in_tmp_VTMS_transition(false),
_is_disable_suspend(false),
_VTMS_transition_mark(false),
#ifdef ASSERT
_is_VTMS_transition_disabler(false),
#endif
#endif
_jni_attach_state(_not_attaching_via_jni),
_is_in_internal_oome_mark(false),
#if INCLUDE_JVMCI
_pending_deoptimization(-1),
_pending_monitorenter(false),
_pending_transfer_to_interpreter(false),
_pending_failed_speculation(0),
_jvmci{nullptr},
_libjvmci_runtime(nullptr),
_jvmci_counters(nullptr),
_jvmci_reserved0(0),
_jvmci_reserved1(0),
_jvmci_reserved_oop0(nullptr),
_live_nmethod(nullptr),
#endif // INCLUDE_JVMCI
_exception_oop(oop()),
_exception_pc(nullptr),
_exception_handler_pc(nullptr),
_is_method_handle_return(0),
_jni_active_critical(0),
_pending_jni_exception_check_fn(nullptr),
_depth_first_number(0),
// JVMTI PopFrame support
_popframe_condition(popframe_inactive),
_frames_to_pop_failed_realloc(0),
_cont_entry(nullptr),
_cont_fastpath(nullptr),
_cont_fastpath_thread_state(1),
_held_monitor_count(0),
_jni_monitor_count(0),
_handshake(this),
_popframe_preserved_args(nullptr),
_popframe_preserved_args_size(0),
_jvmti_thread_state(nullptr),
_interp_only_mode(0),
_should_post_on_exceptions_flag(JNI_FALSE),
_thread_stat(new ThreadStatistics()),
_parker(),
_class_to_be_initialized(nullptr),
_SleepEvent(ParkEvent::Allocate(this)),
_lock_stack(this),
_om_cache(this) {
set_jni_functions(jni_functions());
#if INCLUDE_JVMCI
assert(_jvmci._implicit_exception_pc == nullptr, "must be");
if (JVMCICounterSize > 0) {
resize_counters(0, (int) JVMCICounterSize);
}
#endif // INCLUDE_JVMCI
// Setup safepoint state info for this thread
ThreadSafepointState::create(this);
SafepointMechanism::initialize_header(this);
set_requires_cross_modify_fence(false);
pd_initialize();
assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
}
JavaThread* JavaThread::create_attaching_thread() {
JavaThread* jt = new JavaThread();
jt->_jni_attach_state = _attaching_via_jni;
return jt;
}
// interrupt support
void JavaThread::interrupt() {
// All callers should have 'this' thread protected by a
// ThreadsListHandle so that it cannot terminate and deallocate
// itself.
debug_only(check_for_dangling_thread_pointer(this);)
// For Windows _interrupt_event
WINDOWS_ONLY(osthread()->set_interrupted(true);)
// For Thread.sleep
_SleepEvent->unpark();
// For JSR166 LockSupport.park
parker()->unpark();
// For ObjectMonitor and JvmtiRawMonitor
_ParkEvent->unpark();
}
bool JavaThread::is_interrupted(bool clear_interrupted) {
debug_only(check_for_dangling_thread_pointer(this);)
if (_threadObj.peek() == nullptr) {
// If there is no j.l.Thread then it is impossible to have
// been interrupted. We can find null during VM initialization
// or when a JNI thread is still in the process of attaching.
// In such cases this must be the current thread.
assert(this == Thread::current(), "invariant");
return false;
}
bool interrupted = java_lang_Thread::interrupted(threadObj());
// NOTE that since there is no "lock" around the interrupt and
// is_interrupted operations, there is the possibility that the
// interrupted flag will be "false" but that the
// low-level events will be in the signaled state. This is
// intentional. The effect of this is that Object.wait() and
// LockSupport.park() will appear to have a spurious wakeup, which
// is allowed and not harmful, and the possibility is so rare that
// it is not worth the added complexity to add yet another lock.
// For the sleep event an explicit reset is performed on entry
// to JavaThread::sleep, so there is no early return. It has also been
// recommended not to put the interrupted flag into the "event"
// structure because it hides the issue.
// Also, because there is no lock, we must only clear the interrupt
// state if we are going to report that we were interrupted; otherwise
// an interrupt that happens just after we read the field would be lost.
if (interrupted && clear_interrupted) {
assert(this == Thread::current(), "only the current thread can clear");
java_lang_Thread::set_interrupted(threadObj(), false);
WINDOWS_ONLY(osthread()->set_interrupted(false);)
}
return interrupted;
}
// This is only for use by JVMTI RawMonitorWait. It emulates the actions of
// the Java code in Object::wait which are not present in RawMonitorWait.
bool JavaThread::get_and_clear_interrupted() {
if (!is_interrupted(false)) {
return false;
}
oop thread_oop = vthread_or_thread();
bool is_virtual = java_lang_VirtualThread::is_instance(thread_oop);
if (!is_virtual) {
return is_interrupted(true);
}
// Virtual thread: clear interrupt status for both virtual and
// carrier threads under the interruptLock protection.
JavaThread* current = JavaThread::current();
HandleMark hm(current);
Handle thread_h(current, thread_oop);
ObjectLocker lock(Handle(current, java_lang_Thread::interrupt_lock(thread_h())), current);
// re-check the interrupt status under the interruptLock protection
bool interrupted = java_lang_Thread::interrupted(thread_h());
if (interrupted) {
assert(this == Thread::current(), "only the current thread can clear");
java_lang_Thread::set_interrupted(thread_h(), false); // clear for virtual
java_lang_Thread::set_interrupted(threadObj(), false); // clear for carrier
WINDOWS_ONLY(osthread()->set_interrupted(false);)
}
return interrupted;
}
void JavaThread::block_if_vm_exited() {
if (_terminated == _vm_exited) {
// _vm_exited is set at safepoint, and Threads_lock is never released
// so we will block here forever.
// Here we can be doing a jump from a safe state to an unsafe state without
// proper transition, but it happens after the final safepoint has begun so
// this jump won't cause any safepoint problems.
set_thread_state(_thread_in_vm);
Threads_lock->lock();
ShouldNotReachHere();
}
}
JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz, MemTag mem_tag) : JavaThread(mem_tag) {
set_entry_point(entry_point);
// Create the native thread itself.
// %note runtime_23
os::ThreadType thr_type = os::java_thread;
thr_type = entry_point == &CompilerThread::thread_entry ? os::compiler_thread :
os::java_thread;
os::create_thread(this, thr_type, stack_sz);
// The _osthread may be null here because we ran out of memory (too many threads active).
// We need to throw and OutOfMemoryError - however we cannot do this here because the caller
// may hold a lock and all locks must be unlocked before throwing the exception (throwing
// the exception consists of creating the exception object & initializing it, initialization
// will leave the VM via a JavaCall and then all locks must be unlocked).
//
// The thread is still suspended when we reach here. Thread must be explicit started
// by creator! Furthermore, the thread must also explicitly be added to the Threads list
// by calling Threads:add. The reason why this is not done here, is because the thread
// object must be fully initialized (take a look at JVM_Start)
}
JavaThread::~JavaThread() {
// Enqueue OopHandles for release by the service thread.
add_oop_handles_for_release();
// Return the sleep event to the free list
ParkEvent::Release(_SleepEvent);
_SleepEvent = nullptr;
// Free any remaining previous UnrollBlock
vframeArray* old_array = vframe_array_last();
if (old_array != nullptr) {
Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
old_array->set_unroll_block(nullptr);
delete old_info;
delete old_array;
}
JvmtiDeferredUpdates* updates = deferred_updates();
if (updates != nullptr) {
// This can only happen if thread is destroyed before deoptimization occurs.
assert(updates->count() > 0, "Updates holder not deleted");
// free deferred updates.
delete updates;
set_deferred_updates(nullptr);
}
// All Java related clean up happens in exit
ThreadSafepointState::destroy(this);
if (_thread_stat != nullptr) delete _thread_stat;
#if INCLUDE_JVMCI
if (JVMCICounterSize > 0) {
FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
}
#endif // INCLUDE_JVMCI
}
// First JavaThread specific code executed by a new Java thread.
void JavaThread::pre_run() {
// empty - see comments in run()
}
// The main routine called by a new Java thread. This isn't overridden
// by subclasses, instead different subclasses define a different "entry_point"
// which defines the actual logic for that kind of thread.
void JavaThread::run() {
// initialize thread-local alloc buffer related fields
initialize_tlab();
_stack_overflow_state.create_stack_guard_pages();
cache_global_variables();
// Thread is now sufficiently initialized to be handled by the safepoint code as being
// in the VM. Change thread state from _thread_new to _thread_in_vm
assert(this->thread_state() == _thread_new, "wrong thread state");
set_thread_state(_thread_in_vm);
// Before a thread is on the threads list it is always safe, so after leaving the
// _thread_new we should emit a instruction barrier. The distance to modified code
// from here is probably far enough, but this is consistent and safe.
OrderAccess::cross_modify_fence();
assert(JavaThread::current() == this, "sanity check");
assert(!Thread::current()->owns_locks(), "sanity check");
DTRACE_THREAD_PROBE(start, this);
// This operation might block. We call that after all safepoint checks for a new thread has
// been completed.
set_active_handles(JNIHandleBlock::allocate_block());
if (JvmtiExport::should_post_thread_life()) {
JvmtiExport::post_thread_start(this);
}
if (AlwaysPreTouchStacks) {
pretouch_stack();
}
// We call another function to do the rest so we are sure that the stack addresses used
// from there will be lower than the stack base just computed.
thread_main_inner();
}
void JavaThread::thread_main_inner() {
assert(JavaThread::current() == this, "sanity check");
assert(_threadObj.peek() != nullptr, "just checking");
// Execute thread entry point unless this thread has a pending exception.
// Note: Due to JVMTI StopThread we can have pending exceptions already!
if (!this->has_pending_exception()) {
{
ResourceMark rm(this);
this->set_native_thread_name(this->name());
}
HandleMark hm(this);
this->entry_point()(this, this);
}
DTRACE_THREAD_PROBE(stop, this);
// Cleanup is handled in post_run()
}
// Shared teardown for all JavaThreads
void JavaThread::post_run() {
this->exit(false);
this->unregister_thread_stack_with_NMT();
// Defer deletion to here to ensure 'this' is still referenceable in call_run
// for any shared tear-down.
this->smr_delete();
}
static void ensure_join(JavaThread* thread) {
// We do not need to grab the Threads_lock, since we are operating on ourself.
Handle threadObj(thread, thread->threadObj());
assert(threadObj.not_null(), "java thread object must exist");
ObjectLocker lock(threadObj, thread);
// Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
java_lang_Thread::set_thread_status(threadObj(), JavaThreadStatus::TERMINATED);
// Clear the native thread instance - this makes isAlive return false and allows the join()
// to complete once we've done the notify_all below. Needs a release() to obey Java Memory Model
// requirements.
assert(java_lang_Thread::thread(threadObj()) == thread, "must be alive");
java_lang_Thread::release_set_thread(threadObj(), nullptr);
lock.notify_all(thread);
// Ignore pending exception, since we are exiting anyway
thread->clear_pending_exception();
}
static bool is_daemon(oop threadObj) {
return (threadObj != nullptr && java_lang_Thread::is_daemon(threadObj));
}
// For any new cleanup additions, please check to see if they need to be applied to
// cleanup_failed_attach_current_thread as well.
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
assert(this == JavaThread::current(), "thread consistency check");
assert(!is_exiting(), "should not be exiting or terminated already");
elapsedTimer _timer_exit_phase1;
elapsedTimer _timer_exit_phase2;
elapsedTimer _timer_exit_phase3;
elapsedTimer _timer_exit_phase4;
om_clear_monitor_cache();
if (log_is_enabled(Debug, os, thread, timer)) {
_timer_exit_phase1.start();
}
HandleMark hm(this);
Handle uncaught_exception(this, this->pending_exception());
this->clear_pending_exception();
Handle threadObj(this, this->threadObj());
assert(threadObj.not_null(), "Java thread object should be created");
if (!destroy_vm) {
if (uncaught_exception.not_null()) {
EXCEPTION_MARK;
// Call method Thread.dispatchUncaughtException().
Klass* thread_klass = vmClasses::Thread_klass();
JavaValue result(T_VOID);
JavaCalls::call_virtual(&result,
threadObj, thread_klass,
vmSymbols::dispatchUncaughtException_name(),
vmSymbols::throwable_void_signature(),
uncaught_exception,
THREAD);
if (HAS_PENDING_EXCEPTION) {
ResourceMark rm(this);
jio_fprintf(defaultStream::error_stream(),
"\nException: %s thrown from the UncaughtExceptionHandler"
" in thread \"%s\"\n",
pending_exception()->klass()->external_name(),
name());
CLEAR_PENDING_EXCEPTION;
}
}
if (!is_Compiler_thread()) {
// We have finished executing user-defined Java code and now have to do the
// implementation specific clean-up by calling Thread.exit(). We prevent any
// asynchronous exceptions from being delivered while in Thread.exit()
// to ensure the clean-up is not corrupted.
NoAsyncExceptionDeliveryMark _no_async(this);
EXCEPTION_MARK;
JavaValue result(T_VOID);
Klass* thread_klass = vmClasses::Thread_klass();
JavaCalls::call_virtual(&result,
threadObj, thread_klass,
vmSymbols::exit_method_name(),
vmSymbols::void_method_signature(),
THREAD);
CLEAR_PENDING_EXCEPTION;
}
// notify JVMTI
if (JvmtiExport::should_post_thread_life()) {
JvmtiExport::post_thread_end(this);
}
} else {
// before_exit() has already posted JVMTI THREAD_END events
}
// Cleanup any pending async exception now since we cannot access oops after
// BarrierSet::barrier_set()->on_thread_detach() has been executed.
if (has_async_exception_condition()) {
handshake_state()->clean_async_exception_operation();
}
// The careful dance between thread suspension and exit is handled here.
// Since we are in thread_in_vm state and suspension is done with handshakes,
// we can just put in the exiting state and it will be correctly handled.
// Also, no more async exceptions will be added to the queue after this point.
set_terminated(_thread_exiting);
ThreadService::current_thread_exiting(this, is_daemon(threadObj()));
if (log_is_enabled(Debug, os, thread, timer)) {
_timer_exit_phase1.stop();
_timer_exit_phase2.start();
}
// Capture daemon status before the thread is marked as terminated.
bool daemon = is_daemon(threadObj());
// Notify waiters on thread object. This has to be done after exit() is called
// on the thread (if the thread is the last thread in a daemon ThreadGroup the
// group should have the destroyed bit set before waiters are notified).
ensure_join(this);
assert(!this->has_pending_exception(), "ensure_join should have cleared");
if (log_is_enabled(Debug, os, thread, timer)) {
_timer_exit_phase2.stop();
_timer_exit_phase3.start();
}
// 6282335 JNI DetachCurrentThread spec states that all Java monitors
// held by this thread must be released. The spec does not distinguish
// between JNI-acquired and regular Java monitors. We can only see
// regular Java monitors here if monitor enter-exit matching is broken.
//
// ensure_join() ignores IllegalThreadStateExceptions, and so does
// ObjectSynchronizer::release_monitors_owned_by_thread().
if (exit_type == jni_detach) {
// Sanity check even though JNI DetachCurrentThread() would have
// returned JNI_ERR if there was a Java frame. JavaThread exit
// should be done executing Java code by the time we get here.
assert(!this->has_last_Java_frame(),
"should not have a Java frame when detaching or exiting");
ObjectSynchronizer::release_monitors_owned_by_thread(this);
assert(!this->has_pending_exception(), "release_monitors should have cleared");
// Check for monitor counts being out of sync.
assert(held_monitor_count() == jni_monitor_count(),
"held monitor count should be equal to jni: " INTX_FORMAT " != " INTX_FORMAT,
held_monitor_count(), jni_monitor_count());
// All in-use monitors, including JNI-locked ones, should have been released above.
assert(held_monitor_count() == 0, "Failed to unlock " INTX_FORMAT " object monitors",
held_monitor_count());
} else {
// Check for monitor counts being out of sync.
assert(held_monitor_count() == jni_monitor_count(),
"held monitor count should be equal to jni: " INTX_FORMAT " != " INTX_FORMAT,
held_monitor_count(), jni_monitor_count());
// It is possible that a terminating thread failed to unlock monitors it locked
// via JNI so we don't assert the count is zero.
}
if (CheckJNICalls && jni_monitor_count() > 0) {
// We would like a fatal here, but due to we never checked this before there
// is a lot of tests which breaks, even with an error log.
log_debug(jni)("JavaThread %s (tid: " UINTX_FORMAT ") with Objects still locked by JNI MonitorEnter.",
exit_type == JavaThread::normal_exit ? "exiting" : "detaching", os::current_thread_id());
}
// These things needs to be done while we are still a Java Thread. Make sure that thread
// is in a consistent state, in case GC happens
JFR_ONLY(Jfr::on_thread_exit(this);)
if (active_handles() != nullptr) {
JNIHandleBlock* block = active_handles();
set_active_handles(nullptr);
JNIHandleBlock::release_block(block);
}
if (free_handle_block() != nullptr) {
JNIHandleBlock* block = free_handle_block();
set_free_handle_block(nullptr);
JNIHandleBlock::release_block(block);
}
// These have to be removed while this is still a valid thread.
_stack_overflow_state.remove_stack_guard_pages();
if (UseTLAB) {
tlab().retire();
}
if (JvmtiEnv::environments_might_exist()) {
JvmtiExport::cleanup_thread(this);
}
// We need to cache the thread name for logging purposes below as once
// we have called on_thread_detach this thread must not access any oops.
char* thread_name = nullptr;
if (log_is_enabled(Debug, os, thread, timer)) {
ResourceMark rm(this);
thread_name = os::strdup(name());
}
if (log_is_enabled(Info, os, thread)) {
ResourceMark rm(this);
log_info(os, thread)("JavaThread %s (name: \"%s\", tid: " UINTX_FORMAT ").",
exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
name(), os::current_thread_id());
}
if (log_is_enabled(Debug, os, thread, timer)) {
_timer_exit_phase3.stop();
_timer_exit_phase4.start();
}
#if INCLUDE_JVMCI
if (JVMCICounterSize > 0) {
if (jvmci_counters_include(this)) {
for (int i = 0; i < JVMCICounterSize; i++) {
_jvmci_old_thread_counters[i] += _jvmci_counters[i];
}
}
}
#endif // INCLUDE_JVMCI
// Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread.
// We call BarrierSet::barrier_set()->on_thread_detach() here so no touching of oops after this point.
Threads::remove(this, daemon);
if (log_is_enabled(Debug, os, thread, timer)) {
_timer_exit_phase4.stop();
log_debug(os, thread, timer)("name='%s'"