< prev index next >

src/hotspot/share/runtime/javaThread.cpp

Print this page

  66 #include "runtime/handles.inline.hpp"
  67 #include "runtime/handshake.hpp"
  68 #include "runtime/interfaceSupport.inline.hpp"
  69 #include "runtime/java.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/javaThread.inline.hpp"
  72 #include "runtime/jniHandles.inline.hpp"
  73 #include "runtime/lockStack.inline.hpp"
  74 #include "runtime/mutexLocker.hpp"
  75 #include "runtime/orderAccess.hpp"
  76 #include "runtime/os.inline.hpp"
  77 #include "runtime/osThread.hpp"
  78 #include "runtime/safepoint.hpp"
  79 #include "runtime/safepointMechanism.inline.hpp"
  80 #include "runtime/safepointVerifiers.hpp"
  81 #include "runtime/serviceThread.hpp"
  82 #include "runtime/stackFrameStream.inline.hpp"
  83 #include "runtime/stackWatermarkSet.hpp"
  84 #include "runtime/synchronizer.hpp"
  85 #include "runtime/threadCritical.hpp"

  86 #include "runtime/threadSMR.inline.hpp"
  87 #include "runtime/threadStatisticalInfo.hpp"
  88 #include "runtime/threadWXSetters.inline.hpp"
  89 #include "runtime/timer.hpp"
  90 #include "runtime/timerTrace.hpp"
  91 #include "runtime/vframe.inline.hpp"
  92 #include "runtime/vframeArray.hpp"
  93 #include "runtime/vframe_hp.hpp"
  94 #include "runtime/vmThread.hpp"
  95 #include "runtime/vmOperations.hpp"
  96 #include "services/threadService.hpp"
  97 #include "utilities/copy.hpp"
  98 #include "utilities/defaultStream.hpp"
  99 #include "utilities/dtrace.hpp"
 100 #include "utilities/events.hpp"
 101 #include "utilities/macros.hpp"
 102 #include "utilities/preserveException.hpp"
 103 #include "utilities/spinYield.hpp"
 104 #include "utilities/vmError.hpp"
 105 #if INCLUDE_JVMCI

 218   // before the java.lang.Thread instance has been created.
 219   if (vthread_oop != nullptr) {
 220     java_lang_Thread::clear_scopedValueBindings(vthread_oop);
 221   }
 222 }
 223 
 224 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
 225                                     bool daemon, TRAPS) {
 226   assert(thread_group.not_null(), "thread group should be specified");
 227   assert(threadObj() == nullptr, "should only create Java thread object once");
 228 
 229   InstanceKlass* ik = vmClasses::Thread_klass();
 230   assert(ik->is_initialized(), "must be");
 231   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 232 
 233   // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
 234   // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 235   // constructor calls Thread.current(), which must be set here.
 236   java_lang_Thread::set_thread(thread_oop(), this);
 237   set_threadOopHandles(thread_oop());


 238 
 239   JavaValue result(T_VOID);
 240   if (thread_name != nullptr) {
 241     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
 242     // Thread gets assigned specified name and null target
 243     JavaCalls::call_special(&result,
 244                             thread_oop,
 245                             ik,
 246                             vmSymbols::object_initializer_name(),
 247                             vmSymbols::threadgroup_string_void_signature(),
 248                             thread_group,
 249                             name,
 250                             CHECK);
 251   } else {
 252     // Thread gets assigned name "Thread-nnn" and null target
 253     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
 254     JavaCalls::call_special(&result,
 255                             thread_oop,
 256                             ik,
 257                             vmSymbols::object_initializer_name(),
 258                             vmSymbols::threadgroup_runnable_void_signature(),
 259                             thread_group,
 260                             Handle(),
 261                             CHECK);
 262   }



 263   os::set_priority(this, NormPriority);
 264 
 265   if (daemon) {
 266     java_lang_Thread::set_daemon(thread_oop());
 267   }
 268 }
 269 
 270 // ======= JavaThread ========
 271 
 272 #if INCLUDE_JVMCI
 273 
 274 jlong* JavaThread::_jvmci_old_thread_counters;
 275 
 276 static bool jvmci_counters_include(JavaThread* thread) {
 277   return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
 278 }
 279 
 280 void JavaThread::collect_counters(jlong* array, int length) {
 281   assert(length == JVMCICounterSize, "wrong value");
 282   for (int i = 0; i < length; i++) {

 412 JavaThread::JavaThread(MemTag mem_tag) :
 413   Thread(mem_tag),
 414   // Initialize fields
 415   _on_thread_list(false),
 416   DEBUG_ONLY(_java_call_counter(0) COMMA)
 417   _entry_point(nullptr),
 418   _deopt_mark(nullptr),
 419   _deopt_nmethod(nullptr),
 420   _vframe_array_head(nullptr),
 421   _vframe_array_last(nullptr),
 422   _jvmti_deferred_updates(nullptr),
 423   _callee_target(nullptr),
 424   _vm_result(nullptr),
 425   _vm_result_2(nullptr),
 426 
 427   _current_pending_monitor(nullptr),
 428   _current_pending_monitor_is_from_java(true),
 429   _current_waiting_monitor(nullptr),
 430   _active_handles(nullptr),
 431   _free_handle_block(nullptr),

 432 
 433   _suspend_flags(0),
 434 
 435   _thread_state(_thread_new),
 436   _saved_exception_pc(nullptr),
 437 #ifdef ASSERT
 438   _no_safepoint_count(0),
 439   _visited_for_critical_count(false),
 440 #endif
 441 
 442   _terminated(_not_terminated),
 443   _in_deopt_handler(0),
 444   _doing_unsafe_access(false),
 445   _do_not_unlock_if_synchronized(false),
 446 #if INCLUDE_JVMTI
 447   _carrier_thread_suspended(false),
 448   _is_in_VTMS_transition(false),
 449   _is_disable_suspend(false),
 450   _VTMS_transition_mark(false),


 451 #ifdef ASSERT
 452   _is_VTMS_transition_disabler(false),
 453 #endif
 454 #endif
 455   _jni_attach_state(_not_attaching_via_jni),
 456   _is_in_internal_oome_mark(false),
 457 #if INCLUDE_JVMCI
 458   _pending_deoptimization(-1),
 459   _pending_monitorenter(false),
 460   _pending_transfer_to_interpreter(false),
 461   _pending_failed_speculation(0),
 462   _jvmci{nullptr},
 463   _libjvmci_runtime(nullptr),
 464   _jvmci_counters(nullptr),
 465   _jvmci_reserved0(0),
 466   _jvmci_reserved1(0),
 467   _jvmci_reserved_oop0(nullptr),
 468   _live_nmethod(nullptr),
 469 #endif // INCLUDE_JVMCI
 470 
 471   _exception_oop(oop()),
 472   _exception_pc(nullptr),
 473   _exception_handler_pc(nullptr),
 474   _is_method_handle_return(0),
 475 
 476   _jni_active_critical(0),
 477   _pending_jni_exception_check_fn(nullptr),
 478   _depth_first_number(0),
 479 
 480   // JVMTI PopFrame support
 481   _popframe_condition(popframe_inactive),
 482   _frames_to_pop_failed_realloc(0),
 483 
 484   _cont_entry(nullptr),
 485   _cont_fastpath(nullptr),
 486   _cont_fastpath_thread_state(1),
 487   _held_monitor_count(0),
 488   _jni_monitor_count(0),
 489   _unlocked_inflated_monitor(nullptr),
 490 




 491   _handshake(this),
 492 
 493   _popframe_preserved_args(nullptr),
 494   _popframe_preserved_args_size(0),
 495 
 496   _jvmti_thread_state(nullptr),
 497   _interp_only_mode(0),
 498   _should_post_on_exceptions_flag(JNI_FALSE),
 499   _thread_stat(new ThreadStatistics()),
 500 
 501   _parker(),
 502 
 503   _class_to_be_initialized(nullptr),

 504 
 505   _SleepEvent(ParkEvent::Allocate(this)),
 506 
 507   _lock_stack(this),
 508   _om_cache(this) {
 509   set_jni_functions(jni_functions());
 510 
 511 #if INCLUDE_JVMCI
 512   assert(_jvmci._implicit_exception_pc == nullptr, "must be");
 513   if (JVMCICounterSize > 0) {
 514     resize_counters(0, (int) JVMCICounterSize);
 515   }
 516 #endif // INCLUDE_JVMCI
 517 
 518   // Setup safepoint state info for this thread
 519   ThreadSafepointState::create(this);
 520 
 521   SafepointMechanism::initialize_header(this);
 522 
 523   set_requires_cross_modify_fence(false);

1145     HandshakeClosure("InstallAsyncException"), _aeh(aeh) {}
1146   ~InstallAsyncExceptionHandshake() {
1147     // If InstallAsyncExceptionHandshake was never executed we need to clean up _aeh.
1148     delete _aeh;
1149   }
1150   void do_thread(Thread* thr) {
1151     JavaThread* target = JavaThread::cast(thr);
1152     target->install_async_exception(_aeh);
1153     _aeh = nullptr;
1154   }
1155 };
1156 
1157 void JavaThread::send_async_exception(JavaThread* target, oop java_throwable) {
1158   OopHandle e(Universe::vm_global(), java_throwable);
1159   InstallAsyncExceptionHandshake iaeh(new AsyncExceptionHandshake(e));
1160   Handshake::execute(&iaeh, target);
1161 }
1162 
1163 #if INCLUDE_JVMTI
1164 void JavaThread::set_is_in_VTMS_transition(bool val) {

1165   _is_in_VTMS_transition = val;
1166 }
1167 
1168 #ifdef ASSERT
1169 void JavaThread::set_is_VTMS_transition_disabler(bool val) {
1170   _is_VTMS_transition_disabler = val;
1171 }
1172 #endif
1173 #endif
1174 
1175 // External suspension mechanism.
1176 //
1177 // Guarantees on return (for a valid target thread):
1178 //   - Target thread will not execute any new bytecode.
1179 //   - Target thread will not enter any new monitors.
1180 //
1181 bool JavaThread::java_suspend() {
1182 #if INCLUDE_JVMTI
1183   // Suspending a JavaThread in VTMS transition or disabling VTMS transitions can cause deadlocks.
1184   assert(!is_in_VTMS_transition(), "no suspend allowed in VTMS transition");

1508 void JavaThread::print_thread_state_on(outputStream *st) const {
1509   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
1510 }
1511 
1512 // Called by Threads::print() for VM_PrintThreads operation
1513 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
1514   st->print_raw("\"");
1515   st->print_raw(name());
1516   st->print_raw("\" ");
1517   oop thread_oop = threadObj();
1518   if (thread_oop != nullptr) {
1519     st->print("#" INT64_FORMAT " [%ld] ", (int64_t)java_lang_Thread::thread_id(thread_oop), (long) osthread()->thread_id());
1520     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
1521     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
1522   }
1523   Thread::print_on(st, print_extended_info);
1524   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
1525   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
1526   if (thread_oop != nullptr) {
1527     if (is_vthread_mounted()) {
1528       oop vt = vthread();
1529       assert(vt != nullptr, "");
1530       st->print_cr("   Carrying virtual thread #" INT64_FORMAT, (int64_t)java_lang_Thread::thread_id(vt));
1531     } else {
1532       st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
1533     }
1534   }
1535 #ifndef PRODUCT
1536   _safepoint_state->print_on(st);
1537 #endif // PRODUCT
1538   if (is_Compiler_thread()) {
1539     CompileTask *task = ((CompilerThread*)this)->task();
1540     if (task != nullptr) {
1541       st->print("   Compiling: ");
1542       task->print(st, nullptr, true, false);
1543     } else {
1544       st->print("   No compile task");
1545     }
1546     st->cr();
1547   }
1548 }
1549 
1550 void JavaThread::print() const { print_on(tty); }

1694   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1695   assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
1696   // Link Java Thread object <-> C++ Thread
1697 
1698   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
1699   // and put it into a new Handle.  The Handle "thread_oop" can then
1700   // be used to pass the C++ thread object to other methods.
1701 
1702   // Set the Java level thread object (jthread) field of the
1703   // new thread (a JavaThread *) to C++ thread object using the
1704   // "thread_oop" handle.
1705 
1706   // Set the thread field (a JavaThread *) of the
1707   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
1708 
1709   Handle thread_oop(Thread::current(),
1710                     JNIHandles::resolve_non_null(jni_thread));
1711   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
1712          "must be initialized");
1713   set_threadOopHandles(thread_oop());

1714 
1715   if (prio == NoPriority) {
1716     prio = java_lang_Thread::priority(thread_oop());
1717     assert(prio != NoPriority, "A valid priority should be present");
1718   }
1719 
1720   // Push the Java priority down to the native thread; needs Threads_lock
1721   Thread::set_priority(this, prio);
1722 
1723   // Add the new thread to the Threads list and set it in motion.
1724   // We must have threads lock in order to call Threads::add.
1725   // It is crucial that we do not block before the thread is
1726   // added to the Threads list for if a GC happens, then the java_thread oop
1727   // will not be visited by GC.
1728   Threads::add(this);
1729   // Publish the JavaThread* in java.lang.Thread after the JavaThread* is
1730   // on a ThreadsList. We don't want to wait for the release when the
1731   // Theads_lock is dropped somewhere in the caller since the JavaThread*
1732   // is already visible to JVM/TI via the ThreadsList.
1733   java_lang_Thread::release_set_thread(thread_oop(), this);

1973 
1974 void JavaThread::trace_stack() {
1975   if (!has_last_Java_frame()) return;
1976   Thread* current_thread = Thread::current();
1977   ResourceMark rm(current_thread);
1978   HandleMark hm(current_thread);
1979   RegisterMap reg_map(this,
1980                       RegisterMap::UpdateMap::include,
1981                       RegisterMap::ProcessFrames::include,
1982                       RegisterMap::WalkContinuation::skip);
1983   trace_stack_from(last_java_vframe(&reg_map));
1984 }
1985 
1986 
1987 #endif // PRODUCT
1988 
1989 // Slow-path increment of the held monitor counts. JNI locking is always
1990 // this slow-path.
1991 void JavaThread::inc_held_monitor_count(intx i, bool jni) {
1992 #ifdef SUPPORT_MONITOR_COUNT








1993   assert(_held_monitor_count >= 0, "Must always be non-negative: " INTX_FORMAT, _held_monitor_count);
1994   _held_monitor_count += i;
1995   if (jni) {
1996     assert(_jni_monitor_count >= 0, "Must always be non-negative: " INTX_FORMAT, _jni_monitor_count);
1997     _jni_monitor_count += i;
1998   }
1999   assert(_held_monitor_count >= _jni_monitor_count, "Monitor count discrepancy detected - held count "
2000          INTX_FORMAT " is less than JNI count " INTX_FORMAT, _held_monitor_count, _jni_monitor_count);
2001 #endif
2002 }
2003 
2004 // Slow-path decrement of the held monitor counts. JNI unlocking is always
2005 // this slow-path.
2006 void JavaThread::dec_held_monitor_count(intx i, bool jni) {
2007 #ifdef SUPPORT_MONITOR_COUNT








2008   _held_monitor_count -= i;
2009   assert(_held_monitor_count >= 0, "Must always be greater than 0: " INTX_FORMAT, _held_monitor_count);
2010   if (jni) {
2011     _jni_monitor_count -= i;
2012     assert(_jni_monitor_count >= 0, "Must always be greater than 0: " INTX_FORMAT, _jni_monitor_count);
2013   }
2014   // When a thread is detaching with still owned JNI monitors, the logic that releases
2015   // the monitors doesn't know to set the "jni" flag and so the counts can get out of sync.
2016   // So we skip this assert if the thread is exiting. Once all monitors are unlocked the
2017   // JNI count is directly set to zero.
2018   assert(_held_monitor_count >= _jni_monitor_count || is_exiting(), "Monitor count discrepancy detected - held count "
2019          INTX_FORMAT " is less than JNI count " INTX_FORMAT, _held_monitor_count, _jni_monitor_count);
2020 #endif
2021 }
2022 
2023 frame JavaThread::vthread_last_frame() {
2024   assert (is_vthread_mounted(), "Virtual thread not mounted");
2025   return last_frame();
2026 }
2027 
2028 frame JavaThread::carrier_last_frame(RegisterMap* reg_map) {
2029   const ContinuationEntry* entry = vthread_continuation();
2030   guarantee (entry != nullptr, "Not a carrier thread");
2031   frame f = entry->to_frame();
2032   if (reg_map->process_frames()) {
2033     entry->flush_stack_processing(this);
2034   }
2035   entry->update_register_map(reg_map);
2036   return f.sender(reg_map);
2037 }
2038 
2039 frame JavaThread::platform_thread_last_frame(RegisterMap* reg_map) {
2040   return is_vthread_mounted() ? carrier_last_frame(reg_map) : last_frame();

2182 // bound to the given java.lang.Thread instance.
2183 // The Threads_lock is held for the duration.
2184 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target,
2185                                        Handle thread_oop, ThreadPriority prio) {
2186 
2187   assert(target->osthread() != nullptr, "target thread is not properly initialized");
2188 
2189   MutexLocker mu(current, Threads_lock);
2190 
2191   // Initialize the fields of the thread_oop first.
2192   if (prio != NoPriority) {
2193     java_lang_Thread::set_priority(thread_oop(), prio);
2194     // Note: we don't call os::set_priority here. Possibly we should,
2195     // else all threads should call it themselves when they first run.
2196   }
2197 
2198   java_lang_Thread::set_daemon(thread_oop());
2199 
2200   // Now bind the thread_oop to the target JavaThread.
2201   target->set_threadOopHandles(thread_oop());

2202 
2203   Threads::add(target); // target is now visible for safepoint/handshake
2204   // Publish the JavaThread* in java.lang.Thread after the JavaThread* is
2205   // on a ThreadsList. We don't want to wait for the release when the
2206   // Theads_lock is dropped when the 'mu' destructor is run since the
2207   // JavaThread* is already visible to JVM/TI via the ThreadsList.
2208 
2209   assert(java_lang_Thread::thread(thread_oop()) == nullptr, "must not be alive");
2210   java_lang_Thread::release_set_thread(thread_oop(), target); // isAlive == true now
2211   Thread::start(target);
2212 }
2213 
2214 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) {
2215   // At this point it may be possible that no osthread was created for the
2216   // JavaThread due to lack of resources. However, since this must work
2217   // for critical system threads just check and abort if this fails.
2218   if (thread->osthread() == nullptr) {
2219     // This isn't really an OOM condition, but historically this is what
2220     // we report.
2221     vm_exit_during_initialization("java.lang.OutOfMemoryError",

2278   assert(!SafepointSynchronize::is_at_safepoint(), "cannot be called at a safepoint");
2279 
2280   while (list != nullptr) {
2281     OopHandleList* l = list;
2282     list = l->next();
2283     delete l;
2284   }
2285 }
2286 
2287 // Add our OopHandles for later release.
2288 void JavaThread::add_oop_handles_for_release() {
2289   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
2290   OopHandleList* new_head = new OopHandleList(_oop_handle_list);
2291   new_head->add(_threadObj);
2292   new_head->add(_vthread);
2293   new_head->add(_jvmti_vthread);
2294   new_head->add(_scopedValueCache);
2295   _oop_handle_list = new_head;
2296   Service_lock->notify_all();
2297 }




































  66 #include "runtime/handles.inline.hpp"
  67 #include "runtime/handshake.hpp"
  68 #include "runtime/interfaceSupport.inline.hpp"
  69 #include "runtime/java.hpp"
  70 #include "runtime/javaCalls.hpp"
  71 #include "runtime/javaThread.inline.hpp"
  72 #include "runtime/jniHandles.inline.hpp"
  73 #include "runtime/lockStack.inline.hpp"
  74 #include "runtime/mutexLocker.hpp"
  75 #include "runtime/orderAccess.hpp"
  76 #include "runtime/os.inline.hpp"
  77 #include "runtime/osThread.hpp"
  78 #include "runtime/safepoint.hpp"
  79 #include "runtime/safepointMechanism.inline.hpp"
  80 #include "runtime/safepointVerifiers.hpp"
  81 #include "runtime/serviceThread.hpp"
  82 #include "runtime/stackFrameStream.inline.hpp"
  83 #include "runtime/stackWatermarkSet.hpp"
  84 #include "runtime/synchronizer.hpp"
  85 #include "runtime/threadCritical.hpp"
  86 #include "runtime/threadIdentifier.hpp"
  87 #include "runtime/threadSMR.inline.hpp"
  88 #include "runtime/threadStatisticalInfo.hpp"
  89 #include "runtime/threadWXSetters.inline.hpp"
  90 #include "runtime/timer.hpp"
  91 #include "runtime/timerTrace.hpp"
  92 #include "runtime/vframe.inline.hpp"
  93 #include "runtime/vframeArray.hpp"
  94 #include "runtime/vframe_hp.hpp"
  95 #include "runtime/vmThread.hpp"
  96 #include "runtime/vmOperations.hpp"
  97 #include "services/threadService.hpp"
  98 #include "utilities/copy.hpp"
  99 #include "utilities/defaultStream.hpp"
 100 #include "utilities/dtrace.hpp"
 101 #include "utilities/events.hpp"
 102 #include "utilities/macros.hpp"
 103 #include "utilities/preserveException.hpp"
 104 #include "utilities/spinYield.hpp"
 105 #include "utilities/vmError.hpp"
 106 #if INCLUDE_JVMCI

 219   // before the java.lang.Thread instance has been created.
 220   if (vthread_oop != nullptr) {
 221     java_lang_Thread::clear_scopedValueBindings(vthread_oop);
 222   }
 223 }
 224 
 225 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
 226                                     bool daemon, TRAPS) {
 227   assert(thread_group.not_null(), "thread group should be specified");
 228   assert(threadObj() == nullptr, "should only create Java thread object once");
 229 
 230   InstanceKlass* ik = vmClasses::Thread_klass();
 231   assert(ik->is_initialized(), "must be");
 232   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 233 
 234   // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
 235   // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 236   // constructor calls Thread.current(), which must be set here.
 237   java_lang_Thread::set_thread(thread_oop(), this);
 238   set_threadOopHandles(thread_oop());
 239   // Set the lock_id to the next thread_id temporarily while initialization runs.
 240   set_lock_id(ThreadIdentifier::next());
 241 
 242   JavaValue result(T_VOID);
 243   if (thread_name != nullptr) {
 244     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
 245     // Thread gets assigned specified name and null target
 246     JavaCalls::call_special(&result,
 247                             thread_oop,
 248                             ik,
 249                             vmSymbols::object_initializer_name(),
 250                             vmSymbols::threadgroup_string_void_signature(),
 251                             thread_group,
 252                             name,
 253                             CHECK);
 254   } else {
 255     // Thread gets assigned name "Thread-nnn" and null target
 256     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
 257     JavaCalls::call_special(&result,
 258                             thread_oop,
 259                             ik,
 260                             vmSymbols::object_initializer_name(),
 261                             vmSymbols::threadgroup_runnable_void_signature(),
 262                             thread_group,
 263                             Handle(),
 264                             CHECK);
 265   }
 266   // Update the lock_id with the tid value.
 267   set_lock_id(java_lang_Thread::thread_id(thread_oop()));
 268 
 269   os::set_priority(this, NormPriority);
 270 
 271   if (daemon) {
 272     java_lang_Thread::set_daemon(thread_oop());
 273   }
 274 }
 275 
 276 // ======= JavaThread ========
 277 
 278 #if INCLUDE_JVMCI
 279 
 280 jlong* JavaThread::_jvmci_old_thread_counters;
 281 
 282 static bool jvmci_counters_include(JavaThread* thread) {
 283   return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
 284 }
 285 
 286 void JavaThread::collect_counters(jlong* array, int length) {
 287   assert(length == JVMCICounterSize, "wrong value");
 288   for (int i = 0; i < length; i++) {

 418 JavaThread::JavaThread(MemTag mem_tag) :
 419   Thread(mem_tag),
 420   // Initialize fields
 421   _on_thread_list(false),
 422   DEBUG_ONLY(_java_call_counter(0) COMMA)
 423   _entry_point(nullptr),
 424   _deopt_mark(nullptr),
 425   _deopt_nmethod(nullptr),
 426   _vframe_array_head(nullptr),
 427   _vframe_array_last(nullptr),
 428   _jvmti_deferred_updates(nullptr),
 429   _callee_target(nullptr),
 430   _vm_result(nullptr),
 431   _vm_result_2(nullptr),
 432 
 433   _current_pending_monitor(nullptr),
 434   _current_pending_monitor_is_from_java(true),
 435   _current_waiting_monitor(nullptr),
 436   _active_handles(nullptr),
 437   _free_handle_block(nullptr),
 438   _lock_id(0),
 439 
 440   _suspend_flags(0),
 441 
 442   _thread_state(_thread_new),
 443   _saved_exception_pc(nullptr),
 444 #ifdef ASSERT
 445   _no_safepoint_count(0),
 446   _visited_for_critical_count(false),
 447 #endif
 448 
 449   _terminated(_not_terminated),
 450   _in_deopt_handler(0),
 451   _doing_unsafe_access(false),
 452   _do_not_unlock_if_synchronized(false),
 453 #if INCLUDE_JVMTI
 454   _carrier_thread_suspended(false),
 455   _is_in_VTMS_transition(false),
 456   _is_disable_suspend(false),
 457   _VTMS_transition_mark(false),
 458   _on_monitor_waited_event(false),
 459   _contended_entered_monitor(nullptr),
 460 #ifdef ASSERT
 461   _is_VTMS_transition_disabler(false),
 462 #endif
 463 #endif
 464   _jni_attach_state(_not_attaching_via_jni),
 465   _is_in_internal_oome_mark(false),
 466 #if INCLUDE_JVMCI
 467   _pending_deoptimization(-1),
 468   _pending_monitorenter(false),
 469   _pending_transfer_to_interpreter(false),
 470   _pending_failed_speculation(0),
 471   _jvmci{nullptr},
 472   _libjvmci_runtime(nullptr),
 473   _jvmci_counters(nullptr),
 474   _jvmci_reserved0(0),
 475   _jvmci_reserved1(0),
 476   _jvmci_reserved_oop0(nullptr),
 477   _live_nmethod(nullptr),
 478 #endif // INCLUDE_JVMCI
 479 
 480   _exception_oop(oop()),
 481   _exception_pc(nullptr),
 482   _exception_handler_pc(nullptr),
 483   _is_method_handle_return(0),
 484 
 485   _jni_active_critical(0),
 486   _pending_jni_exception_check_fn(nullptr),
 487   _depth_first_number(0),
 488 
 489   // JVMTI PopFrame support
 490   _popframe_condition(popframe_inactive),
 491   _frames_to_pop_failed_realloc(0),
 492 
 493   _cont_entry(nullptr),
 494   _cont_fastpath(nullptr),
 495   _cont_fastpath_thread_state(1),
 496   _held_monitor_count(0),
 497   _jni_monitor_count(0),
 498   _unlocked_inflated_monitor(nullptr),
 499 
 500   _preempt_alternate_return(nullptr),
 501   _preemption_cancelled(false),
 502   _pending_interrupted_exception(false),
 503 
 504   _handshake(this),
 505 
 506   _popframe_preserved_args(nullptr),
 507   _popframe_preserved_args_size(0),
 508 
 509   _jvmti_thread_state(nullptr),
 510   _interp_only_mode(0),
 511   _should_post_on_exceptions_flag(JNI_FALSE),
 512   _thread_stat(new ThreadStatistics()),
 513 
 514   _parker(),
 515 
 516   _class_to_be_initialized(nullptr),
 517   _class_being_initialized(nullptr),
 518 
 519   _SleepEvent(ParkEvent::Allocate(this)),
 520 
 521   _lock_stack(this),
 522   _om_cache(this) {
 523   set_jni_functions(jni_functions());
 524 
 525 #if INCLUDE_JVMCI
 526   assert(_jvmci._implicit_exception_pc == nullptr, "must be");
 527   if (JVMCICounterSize > 0) {
 528     resize_counters(0, (int) JVMCICounterSize);
 529   }
 530 #endif // INCLUDE_JVMCI
 531 
 532   // Setup safepoint state info for this thread
 533   ThreadSafepointState::create(this);
 534 
 535   SafepointMechanism::initialize_header(this);
 536 
 537   set_requires_cross_modify_fence(false);

1159     HandshakeClosure("InstallAsyncException"), _aeh(aeh) {}
1160   ~InstallAsyncExceptionHandshake() {
1161     // If InstallAsyncExceptionHandshake was never executed we need to clean up _aeh.
1162     delete _aeh;
1163   }
1164   void do_thread(Thread* thr) {
1165     JavaThread* target = JavaThread::cast(thr);
1166     target->install_async_exception(_aeh);
1167     _aeh = nullptr;
1168   }
1169 };
1170 
1171 void JavaThread::send_async_exception(JavaThread* target, oop java_throwable) {
1172   OopHandle e(Universe::vm_global(), java_throwable);
1173   InstallAsyncExceptionHandshake iaeh(new AsyncExceptionHandshake(e));
1174   Handshake::execute(&iaeh, target);
1175 }
1176 
1177 #if INCLUDE_JVMTI
1178 void JavaThread::set_is_in_VTMS_transition(bool val) {
1179   assert(is_in_VTMS_transition() != val, "already %s transition", val ? "inside" : "outside");
1180   _is_in_VTMS_transition = val;
1181 }
1182 
1183 #ifdef ASSERT
1184 void JavaThread::set_is_VTMS_transition_disabler(bool val) {
1185   _is_VTMS_transition_disabler = val;
1186 }
1187 #endif
1188 #endif
1189 
1190 // External suspension mechanism.
1191 //
1192 // Guarantees on return (for a valid target thread):
1193 //   - Target thread will not execute any new bytecode.
1194 //   - Target thread will not enter any new monitors.
1195 //
1196 bool JavaThread::java_suspend() {
1197 #if INCLUDE_JVMTI
1198   // Suspending a JavaThread in VTMS transition or disabling VTMS transitions can cause deadlocks.
1199   assert(!is_in_VTMS_transition(), "no suspend allowed in VTMS transition");

1523 void JavaThread::print_thread_state_on(outputStream *st) const {
1524   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
1525 }
1526 
1527 // Called by Threads::print() for VM_PrintThreads operation
1528 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
1529   st->print_raw("\"");
1530   st->print_raw(name());
1531   st->print_raw("\" ");
1532   oop thread_oop = threadObj();
1533   if (thread_oop != nullptr) {
1534     st->print("#" INT64_FORMAT " [%ld] ", (int64_t)java_lang_Thread::thread_id(thread_oop), (long) osthread()->thread_id());
1535     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
1536     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
1537   }
1538   Thread::print_on(st, print_extended_info);
1539   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
1540   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
1541   if (thread_oop != nullptr) {
1542     if (is_vthread_mounted()) {
1543       // _lock_id is the thread ID of the mounted virtual thread
1544       st->print_cr("   Carrying virtual thread #" INT64_FORMAT, lock_id());

1545     } else {
1546       st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
1547     }
1548   }
1549 #ifndef PRODUCT
1550   _safepoint_state->print_on(st);
1551 #endif // PRODUCT
1552   if (is_Compiler_thread()) {
1553     CompileTask *task = ((CompilerThread*)this)->task();
1554     if (task != nullptr) {
1555       st->print("   Compiling: ");
1556       task->print(st, nullptr, true, false);
1557     } else {
1558       st->print("   No compile task");
1559     }
1560     st->cr();
1561   }
1562 }
1563 
1564 void JavaThread::print() const { print_on(tty); }

1708   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
1709   assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
1710   // Link Java Thread object <-> C++ Thread
1711 
1712   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
1713   // and put it into a new Handle.  The Handle "thread_oop" can then
1714   // be used to pass the C++ thread object to other methods.
1715 
1716   // Set the Java level thread object (jthread) field of the
1717   // new thread (a JavaThread *) to C++ thread object using the
1718   // "thread_oop" handle.
1719 
1720   // Set the thread field (a JavaThread *) of the
1721   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
1722 
1723   Handle thread_oop(Thread::current(),
1724                     JNIHandles::resolve_non_null(jni_thread));
1725   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
1726          "must be initialized");
1727   set_threadOopHandles(thread_oop());
1728   set_lock_id(java_lang_Thread::thread_id(thread_oop()));
1729 
1730   if (prio == NoPriority) {
1731     prio = java_lang_Thread::priority(thread_oop());
1732     assert(prio != NoPriority, "A valid priority should be present");
1733   }
1734 
1735   // Push the Java priority down to the native thread; needs Threads_lock
1736   Thread::set_priority(this, prio);
1737 
1738   // Add the new thread to the Threads list and set it in motion.
1739   // We must have threads lock in order to call Threads::add.
1740   // It is crucial that we do not block before the thread is
1741   // added to the Threads list for if a GC happens, then the java_thread oop
1742   // will not be visited by GC.
1743   Threads::add(this);
1744   // Publish the JavaThread* in java.lang.Thread after the JavaThread* is
1745   // on a ThreadsList. We don't want to wait for the release when the
1746   // Theads_lock is dropped somewhere in the caller since the JavaThread*
1747   // is already visible to JVM/TI via the ThreadsList.
1748   java_lang_Thread::release_set_thread(thread_oop(), this);

1988 
1989 void JavaThread::trace_stack() {
1990   if (!has_last_Java_frame()) return;
1991   Thread* current_thread = Thread::current();
1992   ResourceMark rm(current_thread);
1993   HandleMark hm(current_thread);
1994   RegisterMap reg_map(this,
1995                       RegisterMap::UpdateMap::include,
1996                       RegisterMap::ProcessFrames::include,
1997                       RegisterMap::WalkContinuation::skip);
1998   trace_stack_from(last_java_vframe(&reg_map));
1999 }
2000 
2001 
2002 #endif // PRODUCT
2003 
2004 // Slow-path increment of the held monitor counts. JNI locking is always
2005 // this slow-path.
2006 void JavaThread::inc_held_monitor_count(intx i, bool jni) {
2007 #ifdef SUPPORT_MONITOR_COUNT
2008 
2009   if (LockingMode != LM_LEGACY) {
2010     // Nothing to do. Just do some sanity check.
2011     assert(_held_monitor_count == 0, "counter should not be used");
2012     assert(_jni_monitor_count == 0, "counter should not be used");
2013     return;
2014   }
2015 
2016   assert(_held_monitor_count >= 0, "Must always be non-negative: " INTX_FORMAT, _held_monitor_count);
2017   _held_monitor_count += i;
2018   if (jni) {
2019     assert(_jni_monitor_count >= 0, "Must always be non-negative: " INTX_FORMAT, _jni_monitor_count);
2020     _jni_monitor_count += i;
2021   }
2022   assert(_held_monitor_count >= _jni_monitor_count, "Monitor count discrepancy detected - held count "
2023          INTX_FORMAT " is less than JNI count " INTX_FORMAT, _held_monitor_count, _jni_monitor_count);
2024 #endif // SUPPORT_MONITOR_COUNT
2025 }
2026 
2027 // Slow-path decrement of the held monitor counts. JNI unlocking is always
2028 // this slow-path.
2029 void JavaThread::dec_held_monitor_count(intx i, bool jni) {
2030 #ifdef SUPPORT_MONITOR_COUNT
2031 
2032   if (LockingMode != LM_LEGACY) {
2033     // Nothing to do. Just do some sanity check.
2034     assert(_held_monitor_count == 0, "counter should not be used");
2035     assert(_jni_monitor_count == 0, "counter should not be used");
2036     return;
2037   }
2038 
2039   _held_monitor_count -= i;
2040   assert(_held_monitor_count >= 0, "Must always be non-negative: " INTX_FORMAT, _held_monitor_count);
2041   if (jni) {
2042     _jni_monitor_count -= i;
2043     assert(_jni_monitor_count >= 0, "Must always be non-negative: " INTX_FORMAT, _jni_monitor_count);
2044   }
2045   // When a thread is detaching with still owned JNI monitors, the logic that releases
2046   // the monitors doesn't know to set the "jni" flag and so the counts can get out of sync.
2047   // So we skip this assert if the thread is exiting. Once all monitors are unlocked the
2048   // JNI count is directly set to zero.
2049   assert(_held_monitor_count >= _jni_monitor_count || is_exiting(), "Monitor count discrepancy detected - held count "
2050          INTX_FORMAT " is less than JNI count " INTX_FORMAT, _held_monitor_count, _jni_monitor_count);
2051 #endif // SUPPORT_MONITOR_COUNT
2052 }
2053 
2054 frame JavaThread::vthread_last_frame() {
2055   assert (is_vthread_mounted(), "Virtual thread not mounted");
2056   return last_frame();
2057 }
2058 
2059 frame JavaThread::carrier_last_frame(RegisterMap* reg_map) {
2060   const ContinuationEntry* entry = vthread_continuation();
2061   guarantee (entry != nullptr, "Not a carrier thread");
2062   frame f = entry->to_frame();
2063   if (reg_map->process_frames()) {
2064     entry->flush_stack_processing(this);
2065   }
2066   entry->update_register_map(reg_map);
2067   return f.sender(reg_map);
2068 }
2069 
2070 frame JavaThread::platform_thread_last_frame(RegisterMap* reg_map) {
2071   return is_vthread_mounted() ? carrier_last_frame(reg_map) : last_frame();

2213 // bound to the given java.lang.Thread instance.
2214 // The Threads_lock is held for the duration.
2215 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target,
2216                                        Handle thread_oop, ThreadPriority prio) {
2217 
2218   assert(target->osthread() != nullptr, "target thread is not properly initialized");
2219 
2220   MutexLocker mu(current, Threads_lock);
2221 
2222   // Initialize the fields of the thread_oop first.
2223   if (prio != NoPriority) {
2224     java_lang_Thread::set_priority(thread_oop(), prio);
2225     // Note: we don't call os::set_priority here. Possibly we should,
2226     // else all threads should call it themselves when they first run.
2227   }
2228 
2229   java_lang_Thread::set_daemon(thread_oop());
2230 
2231   // Now bind the thread_oop to the target JavaThread.
2232   target->set_threadOopHandles(thread_oop());
2233   target->set_lock_id(java_lang_Thread::thread_id(thread_oop()));
2234 
2235   Threads::add(target); // target is now visible for safepoint/handshake
2236   // Publish the JavaThread* in java.lang.Thread after the JavaThread* is
2237   // on a ThreadsList. We don't want to wait for the release when the
2238   // Theads_lock is dropped when the 'mu' destructor is run since the
2239   // JavaThread* is already visible to JVM/TI via the ThreadsList.
2240 
2241   assert(java_lang_Thread::thread(thread_oop()) == nullptr, "must not be alive");
2242   java_lang_Thread::release_set_thread(thread_oop(), target); // isAlive == true now
2243   Thread::start(target);
2244 }
2245 
2246 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) {
2247   // At this point it may be possible that no osthread was created for the
2248   // JavaThread due to lack of resources. However, since this must work
2249   // for critical system threads just check and abort if this fails.
2250   if (thread->osthread() == nullptr) {
2251     // This isn't really an OOM condition, but historically this is what
2252     // we report.
2253     vm_exit_during_initialization("java.lang.OutOfMemoryError",

2310   assert(!SafepointSynchronize::is_at_safepoint(), "cannot be called at a safepoint");
2311 
2312   while (list != nullptr) {
2313     OopHandleList* l = list;
2314     list = l->next();
2315     delete l;
2316   }
2317 }
2318 
2319 // Add our OopHandles for later release.
2320 void JavaThread::add_oop_handles_for_release() {
2321   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
2322   OopHandleList* new_head = new OopHandleList(_oop_handle_list);
2323   new_head->add(_threadObj);
2324   new_head->add(_vthread);
2325   new_head->add(_jvmti_vthread);
2326   new_head->add(_scopedValueCache);
2327   _oop_handle_list = new_head;
2328   Service_lock->notify_all();
2329 }
2330 
2331 #if INCLUDE_JFR
2332 void JavaThread::set_last_freeze_fail_result(freeze_result result) {
2333   assert(result != freeze_ok, "sanity check");
2334   _last_freeze_fail_result = result;
2335   _last_freeze_fail_time = Ticks::now();
2336 }
2337 
2338 // Post jdk.VirtualThreadPinned event
2339 void JavaThread::post_vthread_pinned_event(EventVirtualThreadPinned* event, const char* op, freeze_result result) {
2340   assert(result != freeze_ok, "sanity check");
2341   if (event->should_commit()) {
2342     char reason[256];
2343     if (class_to_be_initialized() != nullptr) {
2344       ResourceMark rm(this);
2345       jio_snprintf(reason, sizeof reason, "Waited for initialization of %s by another thread",
2346                    class_to_be_initialized()->external_name());
2347       event->set_pinnedReason(reason);
2348     } else if (class_being_initialized() != nullptr) {
2349       ResourceMark rm(this);
2350       jio_snprintf(reason, sizeof(reason), "VM call to %s.<clinit> on stack",
2351                    class_being_initialized()->external_name());
2352       event->set_pinnedReason(reason);
2353     } else if (result == freeze_pinned_native) {
2354       event->set_pinnedReason("Native or VM frame on stack");
2355     } else {
2356       jio_snprintf(reason, sizeof(reason), "Freeze or preempt failed (%d)", result);
2357       event->set_pinnedReason(reason);
2358     }
2359     event->set_blockingOperation(op);
2360     event->set_carrierThread(JFR_JVM_THREAD_ID(this));
2361     event->commit();
2362   }
2363 }
2364 #endif
< prev index next >