@@ -78,17 +78,27 @@ inline JvmtiThreadState* JvmtiThreadState::state_for_while_locked(JavaThread *th
78
78
79
79
NoSafepointVerifier nsv; // oop is safe to use.
80
80
81
- if (thread_oop == nullptr ) { // Then thread should not be null (see assert above).
82
- thread_oop = thread->jvmti_vthread () != nullptr ? thread->jvmti_vthread () : thread->threadObj ();
83
- }
84
-
85
81
// In a case of unmounted virtual thread the thread can be null.
86
82
JvmtiThreadState *state = thread == nullptr ? nullptr : thread->jvmti_thread_state ();
87
83
88
- if (state == nullptr && thread != nullptr && thread->is_exiting ()) {
89
- // Don't add a JvmtiThreadState to a thread that is exiting.
84
+ if (state == nullptr && thread != nullptr &&
85
+ (thread->is_exiting () || thread->is_attaching_via_jni ())) {
86
+ // Don't add a JvmtiThreadState to a thread that is exiting or is attaching.
87
+ // When a thread is attaching, it may not have a Java level thread object
88
+ // created yet.
90
89
return nullptr ;
91
90
}
91
+
92
+ // Make sure we don't see an incomplete state. An incomplete state can cause
93
+ // a duplicate JvmtiThreadState being created below and bound to the 'thread'
94
+ // incorrectly, which leads to stale JavaThread* from the JvmtiThreadState
95
+ // after the thread exits.
96
+ assert (state == nullptr || state->get_thread_oop () != nullptr ,
97
+ " incomplete state" );
98
+
99
+ if (thread_oop == nullptr ) { // Then thread should not be null (see assert above).
100
+ thread_oop = thread->jvmti_vthread () != nullptr ? thread->jvmti_vthread () : thread->threadObj ();
101
+ }
92
102
if (state == nullptr || state->get_thread_oop () != thread_oop) {
93
103
// Check if java_lang_Thread already has a link to the JvmtiThreadState.
94
104
if (thread_oop != nullptr ) { // thread_oop can be null during early VMStart.
@@ -98,6 +108,7 @@ inline JvmtiThreadState* JvmtiThreadState::state_for_while_locked(JavaThread *th
98
108
state = new JvmtiThreadState (thread, thread_oop);
99
109
}
100
110
}
111
+ assert (state != nullptr , " sanity check" );
101
112
return state;
102
113
}
103
114
0 commit comments