< 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_mark = 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_mark = 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 
 429   // Notify the barrier set that a thread is being destroyed. Note that a barrier
 430   // set might not be available if we encountered errors during bootstrapping.
 431   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 432   if (barrier_set != NULL) {
 433     barrier_set->on_thread_destroy(this);
 434   }
 435 
 436   // stack_base can be NULL if the thread is never started or exited before
 437   // record_stack_base_and_size called. Although, we would like to ensure
 438   // that all started threads do call record_stack_base_and_size(), there is
 439   // not proper way to enforce that.
 440 #if INCLUDE_NMT
 441   if (_stack_base != NULL) {
 442     MemTracker::release_thread_stack(stack_end(), stack_size());
 443 #ifdef ASSERT
 444     set_stack_base(NULL);
 445 #endif
 446   }
 447 #endif // INCLUDE_NMT
 448 


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


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


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


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




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


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

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


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


1850 }
1851 

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

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


< prev index next >