< prev index next >

src/hotspot/share/runtime/thread.cpp

Print this page




 196 
 197 void Thread::operator delete(void* p) {
 198   if (UseBiasedLocking) {
 199     FreeHeap(((Thread*) p)->_real_malloc_address);
 200   } else {
 201     FreeHeap(p);
 202   }
 203 }
 204 
 205 void JavaThread::smr_delete() {
 206   if (_on_thread_list) {
 207     ThreadsSMRSupport::smr_delete(this);
 208   } else {
 209     delete this;
 210   }
 211 }
 212 
 213 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
 214 // JavaThread
 215 

 216 
 217 Thread::Thread() {



 218   // stack and get_thread
 219   set_stack_base(NULL);
 220   set_stack_size(0);
 221   set_self_raw_id(0);
 222   set_lgrp_id(-1);
 223   DEBUG_ONLY(clear_suspendible_thread();)
 224 
 225   // allocated data structures
 226   set_osthread(NULL);
 227   set_resource_area(new (mtThread)ResourceArea());
 228   DEBUG_ONLY(_current_resource_mark = NULL;)
 229   set_handle_area(new (mtThread) HandleArea(NULL));
 230   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
 231   set_active_handles(NULL);
 232   set_free_handle_block(NULL);
 233   set_last_handle_mark(NULL);
 234   DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL);
 235 
 236   // This initial value ==> never claimed.
 237   _oops_do_parity = 0;


 297     _unhandled_oops = new UnhandledOops(this);
 298   }
 299 #endif // CHECK_UNHANDLED_OOPS
 300 #ifdef ASSERT
 301   if (UseBiasedLocking) {
 302     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
 303     assert(this == _real_malloc_address ||
 304            this == align_up(_real_malloc_address, (int)markOopDesc::biased_lock_alignment),
 305            "bug in forced alignment of thread objects");
 306   }
 307 #endif // ASSERT
 308 
 309   // Notify the barrier set that a thread is being created. The initial
 310   // thread is created before the barrier set is available.  The call to
 311   // BarrierSet::on_thread_create() for this thread is therefore deferred
 312   // to BarrierSet::set_barrier_set().
 313   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 314   if (barrier_set != NULL) {
 315     barrier_set->on_thread_create(this);
 316   } else {
 317 #ifdef ASSERT
 318     static bool initial_thread_created = false;
 319     assert(!initial_thread_created, "creating thread before barrier set");
 320     initial_thread_created = true;
 321 #endif // ASSERT
 322   }
 323 }
 324 
 325 void Thread::initialize_thread_current() {
 326 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 327   assert(_thr_current == NULL, "Thread::current already initialized");
 328   _thr_current = this;
 329 #endif
 330   assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized");
 331   ThreadLocalStorage::set_thread(this);
 332   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 333 }
 334 
 335 void Thread::clear_thread_current() {
 336   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 337 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 338   _thr_current = NULL;
 339 #endif
 340   ThreadLocalStorage::set_thread(NULL);
 341 }


 351 #ifdef SOLARIS
 352   if (os::is_primordial_thread()) {
 353     os::Solaris::correct_stack_boundaries_for_primordial_thread(this);
 354   }
 355 #endif
 356 
 357   // Set stack limits after thread is initialized.
 358   if (is_Java_thread()) {
 359     ((JavaThread*) this)->set_stack_overflow_limit();
 360     ((JavaThread*) this)->set_reserved_stack_activation(stack_base());
 361   }
 362 }
 363 
 364 #if INCLUDE_NMT
 365 void Thread::register_thread_stack_with_NMT() {
 366   MemTracker::record_thread_stack(stack_end(), stack_size());
 367 }
 368 #endif // INCLUDE_NMT
 369 
 370 void Thread::call_run() {


 371   // At this point, Thread object should be fully initialized and
 372   // Thread::current() should be set.
 373 





 374   register_thread_stack_with_NMT();
 375 
 376   JFR_ONLY(Jfr::on_thread_start(this);)
 377 
 378   log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
 379     PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
 380     os::current_thread_id(), p2i(stack_base() - stack_size()),
 381     p2i(stack_base()), stack_size()/1024);
 382 




 383   // Invoke <ChildClass>::run()

 384   this->run();
 385   // Returned from <ChildClass>::run(). Thread finished.
 386 
 387   // Note: at this point the thread object may already have deleted itself.
 388   // So from here on do not dereference *this*.
 389 
 390   // If a thread has not deleted itself ("delete this") as part of its
 391   // termination sequence, we have to ensure thread-local-storage is
 392   // cleared before we actually terminate. No threads should ever be
 393   // deleted asynchronously with respect to their termination.
 394   if (Thread::current_or_null_safe() != NULL) {
 395     assert(Thread::current_or_null_safe() == this, "current thread is wrong");
 396     Thread::clear_thread_current();
 397   }




 398 

 399 }
 400 
 401 Thread::~Thread() {








 402   // Notify the barrier set that a thread is being destroyed. Note that a barrier
 403   // set might not be available if we encountered errors during bootstrapping.
 404   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 405   if (barrier_set != NULL) {
 406     barrier_set->on_thread_destroy(this);
 407   }
 408 
 409   // stack_base can be NULL if the thread is never started or exited before
 410   // record_stack_base_and_size called. Although, we would like to ensure
 411   // that all started threads do call record_stack_base_and_size(), there is
 412   // not proper way to enforce that.
 413 #if INCLUDE_NMT
 414   if (_stack_base != NULL) {
 415     MemTracker::release_thread_stack(stack_end(), stack_size());
 416 #ifdef ASSERT
 417     set_stack_base(NULL);
 418 #endif
 419   }
 420 #endif // INCLUDE_NMT
 421 


 428   assert(last_handle_mark() == NULL, "check we have reached the end");
 429 
 430   // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
 431   // We NULL out the fields for good hygiene.
 432   ParkEvent::Release(_ParkEvent); _ParkEvent   = NULL;
 433   ParkEvent::Release(_SleepEvent); _SleepEvent  = NULL;
 434   ParkEvent::Release(_MutexEvent); _MutexEvent  = NULL;
 435   ParkEvent::Release(_MuxEvent); _MuxEvent    = NULL;
 436 
 437   delete handle_area();
 438   delete metadata_handles();
 439 
 440   // SR_handler uses this as a termination indicator -
 441   // needs to happen before os::free_thread()
 442   delete _SR_lock;
 443   _SR_lock = NULL;
 444 
 445   // osthread() can be NULL, if creation of thread failed.
 446   if (osthread() != NULL) os::free_thread(osthread());
 447 
 448   // clear Thread::current if thread is deleting itself.

 449   // Needed to ensure JNI correctly detects non-attached threads.
 450   if (this == Thread::current()) {
 451     Thread::clear_thread_current();
 452   }
 453 
 454   CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
 455 }
 456 
 457 #ifdef ASSERT
 458 // A JavaThread is considered "dangling" if it is not the current
 459 // thread, has been added the Threads list, the system is not at a
 460 // safepoint and the Thread is not "protected".
 461 //
 462 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
 463   assert(!thread->is_Java_thread() || Thread::current() == thread ||
 464          !((JavaThread *) thread)->on_thread_list() ||
 465          SafepointSynchronize::is_at_safepoint() ||
 466          ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
 467          "possibility of dangling Thread pointer");
 468 }
 469 #endif
 470 


1034 }
1035 
1036 bool Thread::is_in_usable_stack(address adr) const {
1037   size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0;
1038   size_t usable_stack_size = _stack_size - stack_guard_size;
1039 
1040   return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
1041 }
1042 
1043 
1044 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
1045 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
1046 // used for compilation in the future. If that change is made, the need for these methods
1047 // should be revisited, and they should be removed if possible.
1048 
1049 bool Thread::is_lock_owned(address adr) const {
1050   return on_local_stack(adr);
1051 }
1052 
1053 bool Thread::set_as_starting_thread() {


1054   // NOTE: this must be called inside the main thread.

1055   return os::create_main_thread((JavaThread*)this);
1056 }
1057 
1058 static void initialize_class(Symbol* class_name, TRAPS) {
1059   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
1060   InstanceKlass::cast(klass)->initialize(CHECK);
1061 }
1062 
1063 
1064 // Creates the initial ThreadGroup
1065 static Handle create_initial_thread_group(TRAPS) {
1066   Handle system_instance = JavaCalls::construct_new_instance(
1067                             SystemDictionary::ThreadGroup_klass(),
1068                             vmSymbols::void_method_signature(),
1069                             CHECK_NH);
1070   Universe::set_system_thread_group(system_instance());
1071 
1072   Handle string = java_lang_String::create_from_str("main", CHECK_NH);
1073   Handle main_instance = JavaCalls::construct_new_instance(
1074                             SystemDictionary::ThreadGroup_klass(),


1237   List() : _head(NULL), _protect() {}
1238 };
1239 
1240 NonJavaThread::List NonJavaThread::_the_list;
1241 
1242 NonJavaThread::Iterator::Iterator() :
1243   _protect_enter(_the_list._protect.enter()),
1244   _current(OrderAccess::load_acquire(&_the_list._head))
1245 {}
1246 
1247 NonJavaThread::Iterator::~Iterator() {
1248   _the_list._protect.exit(_protect_enter);
1249 }
1250 
1251 void NonJavaThread::Iterator::step() {
1252   assert(!end(), "precondition");
1253   _current = OrderAccess::load_acquire(&_current->_next);
1254 }
1255 
1256 NonJavaThread::NonJavaThread() : Thread(), _next(NULL) {
1257   // Add this thread to _the_list.





1258   MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1259   _next = _the_list._head;
1260   OrderAccess::release_store(&_the_list._head, this);
1261 }
1262 
1263 NonJavaThread::~NonJavaThread() {
1264   JFR_ONLY(Jfr::on_thread_exit(this);)
1265   // Remove this thread from _the_list.
1266   MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1267   NonJavaThread* volatile* p = &_the_list._head;
1268   for (NonJavaThread* t = *p; t != NULL; p = &t->_next, t = *p) {
1269     if (t == this) {
1270       *p = this->_next;
1271       // Wait for any in-progress iterators.

1272       _the_list._protect.synchronize();
1273       break;
1274     }
1275   }
1276 }
1277 

















1278 // NamedThread --  non-JavaThread subclasses with multiple
1279 // uniquely named instances should derive from this.
1280 NamedThread::NamedThread() :
1281   NonJavaThread(),
1282   _name(NULL),
1283   _processed_thread(NULL),
1284   _gc_id(GCId::undefined())
1285 {}
1286 
1287 NamedThread::~NamedThread() {
1288   if (_name != NULL) {
1289     FREE_C_HEAP_ARRAY(char, _name);
1290     _name = NULL;
1291   }
1292 }
1293 
1294 void NamedThread::set_name(const char* format, ...) {
1295   guarantee(_name == NULL, "Only get to set name once.");
1296   _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1297   guarantee(_name != NULL, "alloc failure");
1298   va_list ap;
1299   va_start(ap, format);
1300   jio_vsnprintf(_name, max_name_len, format, ap);
1301   va_end(ap);
1302 }
1303 
1304 void NamedThread::initialize_named_thread() {
1305   set_native_thread_name(name());
1306 }
1307 
1308 void NamedThread::print_on(outputStream* st) const {
1309   st->print("\"%s\" ", name());
1310   Thread::print_on(st);
1311   st->cr();
1312 }
1313 
1314 
1315 // ======= WatcherThread ========
1316 
1317 // The watcher thread exists to simulate timer interrupts.  It should
1318 // be replaced by an abstraction over whatever native support for
1319 // timer interrupts exists on the platform.
1320 
1321 WatcherThread* WatcherThread::_watcher_thread   = NULL;
1322 bool WatcherThread::_startable = false;
1323 volatile bool  WatcherThread::_should_terminate = false;
1324 
1325 WatcherThread::WatcherThread() : NonJavaThread() {
1326   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1327   if (os::create_thread(this, os::watcher_thread)) {


1384 
1385     remaining = PeriodicTask::time_to_wait();
1386     if (remaining == 0) {
1387       // Last task was just disenrolled so loop around and wait until
1388       // another task gets enrolled
1389       continue;
1390     }
1391 
1392     remaining -= time_slept;
1393     if (remaining <= 0) {
1394       break;
1395     }
1396   }
1397 
1398   return time_slept;
1399 }
1400 
1401 void WatcherThread::run() {
1402   assert(this == watcher_thread(), "just checking");
1403 
1404   this->set_native_thread_name(this->name());
1405   this->set_active_handles(JNIHandleBlock::allocate_block());
1406   while (true) {
1407     assert(watcher_thread() == Thread::current(), "thread consistency check");
1408     assert(watcher_thread() == this, "thread consistency check");
1409 
1410     // Calculate how long it'll be until the next PeriodicTask work
1411     // should be done, and sleep that amount of time.
1412     int time_waited = sleep();
1413 
1414     if (VMError::is_error_reported()) {
1415       // A fatal error has happened, the error handler(VMError::report_and_die)
1416       // should abort JVM after creating an error log file. However in some
1417       // rare cases, the error handler itself might deadlock. Here periodically
1418       // check for error reporting timeouts, and if it happens, just proceed to
1419       // abort the VM.
1420 
1421       // This code is in WatcherThread because WatcherThread wakes up
1422       // periodically so the fatal error handler doesn't need to do anything;
1423       // also because the WatcherThread is less likely to crash than other
1424       // threads.


1740     delete deferred;
1741   }
1742 
1743   // All Java related clean up happens in exit
1744   ThreadSafepointState::destroy(this);
1745   if (_thread_stat != NULL) delete _thread_stat;
1746 
1747 #if INCLUDE_JVMCI
1748   if (JVMCICounterSize > 0) {
1749     if (jvmci_counters_include(this)) {
1750       for (int i = 0; i < JVMCICounterSize; i++) {
1751         _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1752       }
1753     }
1754     FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1755   }
1756 #endif // INCLUDE_JVMCI
1757 }
1758 
1759 
1760 // The first routine called by a new Java thread







1761 void JavaThread::run() {
1762   // initialize thread-local alloc buffer related fields
1763   this->initialize_tlab();
1764 
1765   // used to test validity of stack trace backs




1766   this->record_base_of_stack_pointer();
1767 
1768   this->create_stack_guard_pages();
1769 
1770   this->cache_global_variables();
1771 
1772   // Thread is now sufficient initialized to be handled by the safepoint code as being
1773   // in the VM. Change thread state from _thread_new to _thread_in_vm
1774   ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1775 
1776   assert(JavaThread::current() == this, "sanity check");
1777   assert(!Thread::current()->owns_locks(), "sanity check");
1778 
1779   DTRACE_THREAD_PROBE(start, this);
1780 
1781   // This operation might block. We call that after all safepoint checks for a new thread has
1782   // been completed.
1783   this->set_active_handles(JNIHandleBlock::allocate_block());
1784 
1785   if (JvmtiExport::should_post_thread_life()) {
1786     JvmtiExport::post_thread_start(this);
1787 
1788   }
1789 
1790   // We call another function to do the rest so we are sure that the stack addresses used
1791   // from there will be lower than the stack base just computed
1792   thread_main_inner();
1793 
1794   // Note, thread is no longer valid at this point!
1795 }
1796 
1797 
1798 void JavaThread::thread_main_inner() {
1799   assert(JavaThread::current() == this, "sanity check");
1800   assert(this->threadObj() != NULL, "just checking");
1801 
1802   // Execute thread entry point unless this thread has a pending exception
1803   // or has been stopped before starting.
1804   // Note: Due to JVM_StopThread we can have pending exceptions already!
1805   if (!this->has_pending_exception() &&
1806       !java_lang_Thread::is_stillborn(this->threadObj())) {
1807     {
1808       ResourceMark rm(this);
1809       this->set_native_thread_name(this->get_thread_name());
1810     }
1811     HandleMark hm(this);
1812     this->entry_point()(this, this);
1813   }
1814 
1815   DTRACE_THREAD_PROBE(stop, this);
1816 





1817   this->exit(false);


1818   this->smr_delete();
1819 }
1820 
1821 
1822 static void ensure_join(JavaThread* thread) {
1823   // We do not need to grab the Threads_lock, since we are operating on ourself.
1824   Handle threadObj(thread, thread->threadObj());
1825   assert(threadObj.not_null(), "java thread object must exist");
1826   ObjectLocker lock(threadObj, thread);
1827   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1828   thread->clear_pending_exception();
1829   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
1830   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1831   // Clear the native thread instance - this makes isAlive return false and allows the join()
1832   // to complete once we've done the notify_all below
1833   java_lang_Thread::set_thread(threadObj(), NULL);
1834   lock.notify_all(thread);
1835   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1836   thread->clear_pending_exception();
1837 }
1838 
1839 static bool is_daemon(oop threadObj) {
1840   return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj));




 196 
 197 void Thread::operator delete(void* p) {
 198   if (UseBiasedLocking) {
 199     FreeHeap(((Thread*) p)->_real_malloc_address);
 200   } else {
 201     FreeHeap(p);
 202   }
 203 }
 204 
 205 void JavaThread::smr_delete() {
 206   if (_on_thread_list) {
 207     ThreadsSMRSupport::smr_delete(this);
 208   } else {
 209     delete this;
 210   }
 211 }
 212 
 213 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
 214 // JavaThread
 215 
 216 DEBUG_ONLY(Thread* Thread::_starting_thread = NULL;)
 217 
 218 Thread::Thread() {
 219 
 220   DEBUG_ONLY(_run_state = PRE_CALL_RUN;)
 221 
 222   // stack and get_thread
 223   set_stack_base(NULL);
 224   set_stack_size(0);
 225   set_self_raw_id(0);
 226   set_lgrp_id(-1);
 227   DEBUG_ONLY(clear_suspendible_thread();)
 228 
 229   // allocated data structures
 230   set_osthread(NULL);
 231   set_resource_area(new (mtThread)ResourceArea());
 232   DEBUG_ONLY(_current_resource_mark = NULL;)
 233   set_handle_area(new (mtThread) HandleArea(NULL));
 234   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
 235   set_active_handles(NULL);
 236   set_free_handle_block(NULL);
 237   set_last_handle_mark(NULL);
 238   DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL);
 239 
 240   // This initial value ==> never claimed.
 241   _oops_do_parity = 0;


 301     _unhandled_oops = new UnhandledOops(this);
 302   }
 303 #endif // CHECK_UNHANDLED_OOPS
 304 #ifdef ASSERT
 305   if (UseBiasedLocking) {
 306     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
 307     assert(this == _real_malloc_address ||
 308            this == align_up(_real_malloc_address, (int)markOopDesc::biased_lock_alignment),
 309            "bug in forced alignment of thread objects");
 310   }
 311 #endif // ASSERT
 312 
 313   // Notify the barrier set that a thread is being created. The initial
 314   // thread is created before the barrier set is available.  The call to
 315   // BarrierSet::on_thread_create() for this thread is therefore deferred
 316   // to BarrierSet::set_barrier_set().
 317   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 318   if (barrier_set != NULL) {
 319     barrier_set->on_thread_create(this);
 320   } else {
 321     // Only the main thread should be created before the barrier set
 322     // and that happens just before Thread::current is set. No other thread
 323     // can attach as the VM is not created yet, so they can't execute this code.
 324     // If the main thread creates other threads before the barrier set that is an error.
 325     assert(Thread::current_or_null() == NULL, "creating thread before barrier set");
 326   }
 327 }
 328 
 329 void Thread::initialize_thread_current() {
 330 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 331   assert(_thr_current == NULL, "Thread::current already initialized");
 332   _thr_current = this;
 333 #endif
 334   assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized");
 335   ThreadLocalStorage::set_thread(this);
 336   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 337 }
 338 
 339 void Thread::clear_thread_current() {
 340   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 341 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 342   _thr_current = NULL;
 343 #endif
 344   ThreadLocalStorage::set_thread(NULL);
 345 }


 355 #ifdef SOLARIS
 356   if (os::is_primordial_thread()) {
 357     os::Solaris::correct_stack_boundaries_for_primordial_thread(this);
 358   }
 359 #endif
 360 
 361   // Set stack limits after thread is initialized.
 362   if (is_Java_thread()) {
 363     ((JavaThread*) this)->set_stack_overflow_limit();
 364     ((JavaThread*) this)->set_reserved_stack_activation(stack_base());
 365   }
 366 }
 367 
 368 #if INCLUDE_NMT
 369 void Thread::register_thread_stack_with_NMT() {
 370   MemTracker::record_thread_stack(stack_end(), stack_size());
 371 }
 372 #endif // INCLUDE_NMT
 373 
 374 void Thread::call_run() {
 375   DEBUG_ONLY(_run_state = CALL_RUN;)
 376 
 377   // At this point, Thread object should be fully initialized and
 378   // Thread::current() should be set.
 379 
 380   assert(Thread::current_or_null() != NULL, "current thread is unset");
 381   assert(Thread::current_or_null() == this, "current thread is wrong");
 382 
 383   // Perform common initialization actions
 384 
 385   register_thread_stack_with_NMT();
 386 
 387   JFR_ONLY(Jfr::on_thread_start(this);)
 388 
 389   log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
 390     PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
 391     os::current_thread_id(), p2i(stack_base() - stack_size()),
 392     p2i(stack_base()), stack_size()/1024);
 393 
 394   // Perform <ChildClass> initialization actions
 395   DEBUG_ONLY(_run_state = PRE_RUN;)
 396   this->pre_run();
 397 
 398   // Invoke <ChildClass>::run()
 399   DEBUG_ONLY(_run_state = RUN;)
 400   this->run();
 401   // Returned from <ChildClass>::run(). Thread finished.
 402 
 403   // Perform common tear-down actions

 404 
 405   assert(Thread::current_or_null() != NULL, "current thread is unset");
 406   assert(Thread::current_or_null() == this, "current thread is wrong");
 407 
 408   // Perform <ChildClass> tear-down actions
 409   DEBUG_ONLY(_run_state = POST_RUN;)
 410   this->post_run();
 411 
 412   // Note: at this point the thread object may already have deleted itself,
 413   // so from here on do not dereference *this*. Not all thread types currently
 414   // delete themselves when they terminate. But no thread should ever be deleted
 415   // asynchronously with respect to its termination - that is what _run_state can
 416   // be used to check.
 417 
 418   assert(Thread::current_or_null() == NULL, "current thread still present");
 419 }
 420 
 421 Thread::~Thread() {
 422 
 423   // Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually
 424   // get started due to errors etc. Any active thread should at least reach post_run
 425   // before it is deleted (usually in post_run()).
 426   assert(_run_state == PRE_CALL_RUN ||
 427          _run_state == POST_RUN, "Active Thread deleted before post_run(): "
 428          "_run_state=%d", (int)_run_state);
 429 
 430   // Notify the barrier set that a thread is being destroyed. Note that a barrier
 431   // set might not be available if we encountered errors during bootstrapping.
 432   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 433   if (barrier_set != NULL) {
 434     barrier_set->on_thread_destroy(this);
 435   }
 436 
 437   // stack_base can be NULL if the thread is never started or exited before
 438   // record_stack_base_and_size called. Although, we would like to ensure
 439   // that all started threads do call record_stack_base_and_size(), there is
 440   // not proper way to enforce that.
 441 #if INCLUDE_NMT
 442   if (_stack_base != NULL) {
 443     MemTracker::release_thread_stack(stack_end(), stack_size());
 444 #ifdef ASSERT
 445     set_stack_base(NULL);
 446 #endif
 447   }
 448 #endif // INCLUDE_NMT
 449 


 456   assert(last_handle_mark() == NULL, "check we have reached the end");
 457 
 458   // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
 459   // We NULL out the fields for good hygiene.
 460   ParkEvent::Release(_ParkEvent); _ParkEvent   = NULL;
 461   ParkEvent::Release(_SleepEvent); _SleepEvent  = NULL;
 462   ParkEvent::Release(_MutexEvent); _MutexEvent  = NULL;
 463   ParkEvent::Release(_MuxEvent); _MuxEvent    = NULL;
 464 
 465   delete handle_area();
 466   delete metadata_handles();
 467 
 468   // SR_handler uses this as a termination indicator -
 469   // needs to happen before os::free_thread()
 470   delete _SR_lock;
 471   _SR_lock = NULL;
 472 
 473   // osthread() can be NULL, if creation of thread failed.
 474   if (osthread() != NULL) os::free_thread(osthread());
 475 
 476   // Clear Thread::current if thread is deleting itself and it has not
 477   // already been done. This must be done before the memory is deallocated.
 478   // Needed to ensure JNI correctly detects non-attached threads.
 479   if (this == Thread::current_or_null()) {
 480     Thread::clear_thread_current();
 481   }
 482 
 483   CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
 484 }
 485 
 486 #ifdef ASSERT
 487 // A JavaThread is considered "dangling" if it is not the current
 488 // thread, has been added the Threads list, the system is not at a
 489 // safepoint and the Thread is not "protected".
 490 //
 491 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
 492   assert(!thread->is_Java_thread() || Thread::current() == thread ||
 493          !((JavaThread *) thread)->on_thread_list() ||
 494          SafepointSynchronize::is_at_safepoint() ||
 495          ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
 496          "possibility of dangling Thread pointer");
 497 }
 498 #endif
 499 


1063 }
1064 
1065 bool Thread::is_in_usable_stack(address adr) const {
1066   size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0;
1067   size_t usable_stack_size = _stack_size - stack_guard_size;
1068 
1069   return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
1070 }
1071 
1072 
1073 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
1074 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
1075 // used for compilation in the future. If that change is made, the need for these methods
1076 // should be revisited, and they should be removed if possible.
1077 
1078 bool Thread::is_lock_owned(address adr) const {
1079   return on_local_stack(adr);
1080 }
1081 
1082 bool Thread::set_as_starting_thread() {
1083   assert(_starting_thread == NULL, "already initialized: "
1084          "_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread));
1085   // NOTE: this must be called inside the main thread.
1086   DEBUG_ONLY(_starting_thread = this;)
1087   return os::create_main_thread((JavaThread*)this);
1088 }
1089 
1090 static void initialize_class(Symbol* class_name, TRAPS) {
1091   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
1092   InstanceKlass::cast(klass)->initialize(CHECK);
1093 }
1094 
1095 
1096 // Creates the initial ThreadGroup
1097 static Handle create_initial_thread_group(TRAPS) {
1098   Handle system_instance = JavaCalls::construct_new_instance(
1099                             SystemDictionary::ThreadGroup_klass(),
1100                             vmSymbols::void_method_signature(),
1101                             CHECK_NH);
1102   Universe::set_system_thread_group(system_instance());
1103 
1104   Handle string = java_lang_String::create_from_str("main", CHECK_NH);
1105   Handle main_instance = JavaCalls::construct_new_instance(
1106                             SystemDictionary::ThreadGroup_klass(),


1269   List() : _head(NULL), _protect() {}
1270 };
1271 
1272 NonJavaThread::List NonJavaThread::_the_list;
1273 
1274 NonJavaThread::Iterator::Iterator() :
1275   _protect_enter(_the_list._protect.enter()),
1276   _current(OrderAccess::load_acquire(&_the_list._head))
1277 {}
1278 
1279 NonJavaThread::Iterator::~Iterator() {
1280   _the_list._protect.exit(_protect_enter);
1281 }
1282 
1283 void NonJavaThread::Iterator::step() {
1284   assert(!end(), "precondition");
1285   _current = OrderAccess::load_acquire(&_current->_next);
1286 }
1287 
1288 NonJavaThread::NonJavaThread() : Thread(), _next(NULL) {
1289   assert(BarrierSet::barrier_set() != NULL, "NonJavaThread created too soon!");
1290 }
1291 
1292 NonJavaThread::~NonJavaThread() { }
1293 
1294 void NonJavaThread::add_to_the_list() {
1295   MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1296   _next = _the_list._head;
1297   OrderAccess::release_store(&_the_list._head, this);
1298 }
1299 
1300 void NonJavaThread::remove_from_the_list() {


1301   MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1302   NonJavaThread* volatile* p = &_the_list._head;
1303   for (NonJavaThread* t = *p; t != NULL; p = &t->_next, t = *p) {
1304     if (t == this) {
1305       *p = this->_next;
1306       // Wait for any in-progress iterators.  Concurrent synchronize is
1307       // not allowed, so do it while holding the list lock.
1308       _the_list._protect.synchronize();
1309       break;
1310     }
1311   }
1312 }
1313 
1314 void NonJavaThread::pre_run() {
1315   assert(BarrierSet::barrier_set() != NULL, "invariant");
1316   add_to_the_list();
1317 
1318   // This is slightly odd in that NamedThread is a subclass, but
1319   // in fact name() is defined in Thread
1320   assert(this->name() != NULL, "thread name was not set before it was started");
1321   this->set_native_thread_name(this->name());
1322 }
1323 
1324 void NonJavaThread::post_run() {
1325   JFR_ONLY(Jfr::on_thread_exit(this);)
1326   remove_from_the_list();
1327   // Ensure thread-local-storage is cleared before termination.
1328   Thread::clear_thread_current();
1329 }
1330 
1331 // NamedThread --  non-JavaThread subclasses with multiple
1332 // uniquely named instances should derive from this.
1333 NamedThread::NamedThread() :
1334   NonJavaThread(),
1335   _name(NULL),
1336   _processed_thread(NULL),
1337   _gc_id(GCId::undefined())
1338 {}
1339 
1340 NamedThread::~NamedThread() {
1341   if (_name != NULL) {
1342     FREE_C_HEAP_ARRAY(char, _name);
1343     _name = NULL;
1344   }
1345 }
1346 
1347 void NamedThread::set_name(const char* format, ...) {
1348   guarantee(_name == NULL, "Only get to set name once.");
1349   _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1350   guarantee(_name != NULL, "alloc failure");
1351   va_list ap;
1352   va_start(ap, format);
1353   jio_vsnprintf(_name, max_name_len, format, ap);
1354   va_end(ap);
1355 }
1356 




1357 void NamedThread::print_on(outputStream* st) const {
1358   st->print("\"%s\" ", name());
1359   Thread::print_on(st);
1360   st->cr();
1361 }
1362 
1363 
1364 // ======= WatcherThread ========
1365 
1366 // The watcher thread exists to simulate timer interrupts.  It should
1367 // be replaced by an abstraction over whatever native support for
1368 // timer interrupts exists on the platform.
1369 
1370 WatcherThread* WatcherThread::_watcher_thread   = NULL;
1371 bool WatcherThread::_startable = false;
1372 volatile bool  WatcherThread::_should_terminate = false;
1373 
1374 WatcherThread::WatcherThread() : NonJavaThread() {
1375   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1376   if (os::create_thread(this, os::watcher_thread)) {


1433 
1434     remaining = PeriodicTask::time_to_wait();
1435     if (remaining == 0) {
1436       // Last task was just disenrolled so loop around and wait until
1437       // another task gets enrolled
1438       continue;
1439     }
1440 
1441     remaining -= time_slept;
1442     if (remaining <= 0) {
1443       break;
1444     }
1445   }
1446 
1447   return time_slept;
1448 }
1449 
1450 void WatcherThread::run() {
1451   assert(this == watcher_thread(), "just checking");
1452 

1453   this->set_active_handles(JNIHandleBlock::allocate_block());
1454   while (true) {
1455     assert(watcher_thread() == Thread::current(), "thread consistency check");
1456     assert(watcher_thread() == this, "thread consistency check");
1457 
1458     // Calculate how long it'll be until the next PeriodicTask work
1459     // should be done, and sleep that amount of time.
1460     int time_waited = sleep();
1461 
1462     if (VMError::is_error_reported()) {
1463       // A fatal error has happened, the error handler(VMError::report_and_die)
1464       // should abort JVM after creating an error log file. However in some
1465       // rare cases, the error handler itself might deadlock. Here periodically
1466       // check for error reporting timeouts, and if it happens, just proceed to
1467       // abort the VM.
1468 
1469       // This code is in WatcherThread because WatcherThread wakes up
1470       // periodically so the fatal error handler doesn't need to do anything;
1471       // also because the WatcherThread is less likely to crash than other
1472       // threads.


1788     delete deferred;
1789   }
1790 
1791   // All Java related clean up happens in exit
1792   ThreadSafepointState::destroy(this);
1793   if (_thread_stat != NULL) delete _thread_stat;
1794 
1795 #if INCLUDE_JVMCI
1796   if (JVMCICounterSize > 0) {
1797     if (jvmci_counters_include(this)) {
1798       for (int i = 0; i < JVMCICounterSize; i++) {
1799         _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1800       }
1801     }
1802     FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1803   }
1804 #endif // INCLUDE_JVMCI
1805 }
1806 
1807 
1808 // First JavaThread specific code executed by a new Java thread.
1809 void JavaThread::pre_run() {
1810   // empty - see comments in run()
1811 }
1812 
1813 // The main routine called by a new Java thread. This isn't overridden
1814 // by subclasses, instead different subclasses define a different "entry_point"
1815 // which defines the actual logic for that kind of thread.
1816 void JavaThread::run() {
1817   // initialize thread-local alloc buffer related fields
1818   this->initialize_tlab();
1819 
1820   // Used to test validity of stack trace backs.
1821   // This can't be moved into pre_run() else we invalidate
1822   // the requirement that thread_main_inner is lower on
1823   // the stack. Consequently all the initialization logic
1824   // stays here in run() rather than pre_run().
1825   this->record_base_of_stack_pointer();
1826 
1827   this->create_stack_guard_pages();
1828 
1829   this->cache_global_variables();
1830 
1831   // Thread is now sufficiently initialized to be handled by the safepoint code as being
1832   // in the VM. Change thread state from _thread_new to _thread_in_vm
1833   ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1834 
1835   assert(JavaThread::current() == this, "sanity check");
1836   assert(!Thread::current()->owns_locks(), "sanity check");
1837 
1838   DTRACE_THREAD_PROBE(start, this);
1839 
1840   // This operation might block. We call that after all safepoint checks for a new thread has
1841   // been completed.
1842   this->set_active_handles(JNIHandleBlock::allocate_block());
1843 
1844   if (JvmtiExport::should_post_thread_life()) {
1845     JvmtiExport::post_thread_start(this);
1846 
1847   }
1848 
1849   // We call another function to do the rest so we are sure that the stack addresses used
1850   // from there will be lower than the stack base just computed.
1851   thread_main_inner();


1852 }
1853 

1854 void JavaThread::thread_main_inner() {
1855   assert(JavaThread::current() == this, "sanity check");
1856   assert(this->threadObj() != NULL, "just checking");
1857 
1858   // Execute thread entry point unless this thread has a pending exception
1859   // or has been stopped before starting.
1860   // Note: Due to JVM_StopThread we can have pending exceptions already!
1861   if (!this->has_pending_exception() &&
1862       !java_lang_Thread::is_stillborn(this->threadObj())) {
1863     {
1864       ResourceMark rm(this);
1865       this->set_native_thread_name(this->get_thread_name());
1866     }
1867     HandleMark hm(this);
1868     this->entry_point()(this, this);
1869   }
1870 
1871   DTRACE_THREAD_PROBE(stop, this);
1872 
1873   // Cleanup is handled in post_run()
1874 }
1875 
1876 // Shared teardown for all JavaThreads
1877 void JavaThread::post_run() {
1878   this->exit(false);
1879   // Defer deletion to here to ensure 'this' is still referenceable in call_run
1880   // for any shared tear-down.
1881   this->smr_delete();
1882 }

1883 
1884 static void ensure_join(JavaThread* thread) {
1885   // We do not need to grab the Threads_lock, since we are operating on ourself.
1886   Handle threadObj(thread, thread->threadObj());
1887   assert(threadObj.not_null(), "java thread object must exist");
1888   ObjectLocker lock(threadObj, thread);
1889   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1890   thread->clear_pending_exception();
1891   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
1892   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1893   // Clear the native thread instance - this makes isAlive return false and allows the join()
1894   // to complete once we've done the notify_all below
1895   java_lang_Thread::set_thread(threadObj(), NULL);
1896   lock.notify_all(thread);
1897   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1898   thread->clear_pending_exception();
1899 }
1900 
1901 static bool is_daemon(oop threadObj) {
1902   return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj));


< prev index next >