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
235 // This initial value ==> never claimed.
236 _oops_do_parity = 0;
237 _threads_hazard_ptr = NULL;
346 #ifdef SOLARIS
347 if (os::is_primordial_thread()) {
348 os::Solaris::correct_stack_boundaries_for_primordial_thread(this);
349 }
350 #endif
351
352 // Set stack limits after thread is initialized.
353 if (is_Java_thread()) {
354 ((JavaThread*) this)->set_stack_overflow_limit();
355 ((JavaThread*) this)->set_reserved_stack_activation(stack_base());
356 }
357 }
358
359 #if INCLUDE_NMT
360 void Thread::register_thread_stack_with_NMT() {
361 MemTracker::record_thread_stack(stack_end(), stack_size());
362 }
363 #endif // INCLUDE_NMT
364
365 void Thread::call_run() {
366 // At this point, Thread object should be fully initialized and
367 // Thread::current() should be set.
368
369 register_thread_stack_with_NMT();
370
371 JFR_ONLY(Jfr::on_thread_start(this);)
372
373 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
374 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
375 os::current_thread_id(), p2i(stack_base() - stack_size()),
376 p2i(stack_base()), stack_size()/1024);
377
378 // Invoke <ChildClass>::run()
379 this->run();
380 // Returned from <ChildClass>::run(). Thread finished.
381
382 // Note: at this point the thread object may already have deleted itself.
383 // So from here on do not dereference *this*.
384
385 // If a thread has not deleted itself ("delete this") as part of its
386 // termination sequence, we have to ensure thread-local-storage is
387 // cleared before we actually terminate. No threads should ever be
388 // deleted asynchronously with respect to their termination.
389 if (Thread::current_or_null_safe() != NULL) {
390 assert(Thread::current_or_null_safe() == this, "current thread is wrong");
391 Thread::clear_thread_current();
392 }
393
394 }
395
396 Thread::~Thread() {
397 // Notify the barrier set that a thread is being destroyed. Note that a barrier
398 // set might not be available if we encountered errors during bootstrapping.
399 BarrierSet* const barrier_set = BarrierSet::barrier_set();
400 if (barrier_set != NULL) {
401 barrier_set->on_thread_destroy(this);
402 }
403
404 // stack_base can be NULL if the thread is never started or exited before
405 // record_stack_base_and_size called. Although, we would like to ensure
406 // that all started threads do call record_stack_base_and_size(), there is
407 // not proper way to enforce that.
408 #if INCLUDE_NMT
409 if (_stack_base != NULL) {
410 MemTracker::release_thread_stack(stack_end(), stack_size());
411 #ifdef ASSERT
412 set_stack_base(NULL);
413 #endif
414 }
415 #endif // INCLUDE_NMT
416
423 assert(last_handle_mark() == NULL, "check we have reached the end");
424
425 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
426 // We NULL out the fields for good hygiene.
427 ParkEvent::Release(_ParkEvent); _ParkEvent = NULL;
428 ParkEvent::Release(_SleepEvent); _SleepEvent = NULL;
429 ParkEvent::Release(_MutexEvent); _MutexEvent = NULL;
430 ParkEvent::Release(_MuxEvent); _MuxEvent = NULL;
431
432 delete handle_area();
433 delete metadata_handles();
434
435 // SR_handler uses this as a termination indicator -
436 // needs to happen before os::free_thread()
437 delete _SR_lock;
438 _SR_lock = NULL;
439
440 // osthread() can be NULL, if creation of thread failed.
441 if (osthread() != NULL) os::free_thread(osthread());
442
443 // clear Thread::current if thread is deleting itself.
444 // Needed to ensure JNI correctly detects non-attached threads.
445 if (this == Thread::current()) {
446 Thread::clear_thread_current();
447 }
448
449 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
450 }
451
452 #ifdef ASSERT
453 // A JavaThread is considered "dangling" if it is not the current
454 // thread, has been added the Threads list, the system is not at a
455 // safepoint and the Thread is not "protected".
456 //
457 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
458 assert(!thread->is_Java_thread() || Thread::current() == thread ||
459 !((JavaThread *) thread)->on_thread_list() ||
460 SafepointSynchronize::is_at_safepoint() ||
461 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
462 "possibility of dangling Thread pointer");
463 }
464 #endif
465
1029 }
1030
1031 bool Thread::is_in_usable_stack(address adr) const {
1032 size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0;
1033 size_t usable_stack_size = _stack_size - stack_guard_size;
1034
1035 return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
1036 }
1037
1038
1039 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
1040 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
1041 // used for compilation in the future. If that change is made, the need for these methods
1042 // should be revisited, and they should be removed if possible.
1043
1044 bool Thread::is_lock_owned(address adr) const {
1045 return on_local_stack(adr);
1046 }
1047
1048 bool Thread::set_as_starting_thread() {
1049 // NOTE: this must be called inside the main thread.
1050 return os::create_main_thread((JavaThread*)this);
1051 }
1052
1053 static void initialize_class(Symbol* class_name, TRAPS) {
1054 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
1055 InstanceKlass::cast(klass)->initialize(CHECK);
1056 }
1057
1058
1059 // Creates the initial ThreadGroup
1060 static Handle create_initial_thread_group(TRAPS) {
1061 Handle system_instance = JavaCalls::construct_new_instance(
1062 SystemDictionary::ThreadGroup_klass(),
1063 vmSymbols::void_method_signature(),
1064 CHECK_NH);
1065 Universe::set_system_thread_group(system_instance());
1066
1067 Handle string = java_lang_String::create_from_str("main", CHECK_NH);
1068 Handle main_instance = JavaCalls::construct_new_instance(
1069 SystemDictionary::ThreadGroup_klass(),
1231
1232 List() : _head(NULL), _protect() {}
1233 };
1234
1235 NonJavaThread::List NonJavaThread::_the_list;
1236
1237 NonJavaThread::Iterator::Iterator() :
1238 _protect_enter(_the_list._protect.enter()),
1239 _current(OrderAccess::load_acquire(&_the_list._head))
1240 {}
1241
1242 NonJavaThread::Iterator::~Iterator() {
1243 _the_list._protect.exit(_protect_enter);
1244 }
1245
1246 void NonJavaThread::Iterator::step() {
1247 assert(!end(), "precondition");
1248 _current = OrderAccess::load_acquire(&_current->_next);
1249 }
1250
1251 NonJavaThread::NonJavaThread() : Thread(), _next(NULL) {
1252 // Add this thread to _the_list.
1253 MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1254 _next = _the_list._head;
1255 OrderAccess::release_store(&_the_list._head, this);
1256 }
1257
1258 NonJavaThread::~NonJavaThread() {
1259 JFR_ONLY(Jfr::on_thread_exit(this);)
1260 // Remove this thread from _the_list.
1261 MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1262 NonJavaThread* volatile* p = &_the_list._head;
1263 for (NonJavaThread* t = *p; t != NULL; p = &t->_next, t = *p) {
1264 if (t == this) {
1265 *p = this->_next;
1266 // Wait for any in-progress iterators.
1267 _the_list._protect.synchronize();
1268 break;
1269 }
1270 }
1271 }
1272
1273 // NamedThread -- non-JavaThread subclasses with multiple
1274 // uniquely named instances should derive from this.
1275 NamedThread::NamedThread() :
1276 NonJavaThread(),
1277 _name(NULL),
1278 _processed_thread(NULL),
1279 _gc_id(GCId::undefined())
1280 {}
1281
1282 NamedThread::~NamedThread() {
1283 if (_name != NULL) {
1284 FREE_C_HEAP_ARRAY(char, _name);
1285 _name = NULL;
1286 }
1287 }
1288
1289 void NamedThread::set_name(const char* format, ...) {
1290 guarantee(_name == NULL, "Only get to set name once.");
1291 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1292 guarantee(_name != NULL, "alloc failure");
1293 va_list ap;
1294 va_start(ap, format);
1295 jio_vsnprintf(_name, max_name_len, format, ap);
1296 va_end(ap);
1297 }
1298
1299 void NamedThread::initialize_named_thread() {
1300 set_native_thread_name(name());
1301 }
1302
1303 void NamedThread::print_on(outputStream* st) const {
1304 st->print("\"%s\" ", name());
1305 Thread::print_on(st);
1306 st->cr();
1307 }
1308
1309
1310 // ======= WatcherThread ========
1311
1312 // The watcher thread exists to simulate timer interrupts. It should
1313 // be replaced by an abstraction over whatever native support for
1314 // timer interrupts exists on the platform.
1315
1316 WatcherThread* WatcherThread::_watcher_thread = NULL;
1317 bool WatcherThread::_startable = false;
1318 volatile bool WatcherThread::_should_terminate = false;
1319
1320 WatcherThread::WatcherThread() : NonJavaThread() {
1321 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1322 if (os::create_thread(this, os::watcher_thread)) {
1379
1380 remaining = PeriodicTask::time_to_wait();
1381 if (remaining == 0) {
1382 // Last task was just disenrolled so loop around and wait until
1383 // another task gets enrolled
1384 continue;
1385 }
1386
1387 remaining -= time_slept;
1388 if (remaining <= 0) {
1389 break;
1390 }
1391 }
1392
1393 return time_slept;
1394 }
1395
1396 void WatcherThread::run() {
1397 assert(this == watcher_thread(), "just checking");
1398
1399 this->set_native_thread_name(this->name());
1400 this->set_active_handles(JNIHandleBlock::allocate_block());
1401 while (true) {
1402 assert(watcher_thread() == Thread::current(), "thread consistency check");
1403 assert(watcher_thread() == this, "thread consistency check");
1404
1405 // Calculate how long it'll be until the next PeriodicTask work
1406 // should be done, and sleep that amount of time.
1407 int time_waited = sleep();
1408
1409 if (VMError::is_error_reported()) {
1410 // A fatal error has happened, the error handler(VMError::report_and_die)
1411 // should abort JVM after creating an error log file. However in some
1412 // rare cases, the error handler itself might deadlock. Here periodically
1413 // check for error reporting timeouts, and if it happens, just proceed to
1414 // abort the VM.
1415
1416 // This code is in WatcherThread because WatcherThread wakes up
1417 // periodically so the fatal error handler doesn't need to do anything;
1418 // also because the WatcherThread is less likely to crash than other
1419 // threads.
1735 delete deferred;
1736 }
1737
1738 // All Java related clean up happens in exit
1739 ThreadSafepointState::destroy(this);
1740 if (_thread_stat != NULL) delete _thread_stat;
1741
1742 #if INCLUDE_JVMCI
1743 if (JVMCICounterSize > 0) {
1744 if (jvmci_counters_include(this)) {
1745 for (int i = 0; i < JVMCICounterSize; i++) {
1746 _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1747 }
1748 }
1749 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1750 }
1751 #endif // INCLUDE_JVMCI
1752 }
1753
1754
1755 // The first routine called by a new Java thread
1756 void JavaThread::run() {
1757 // initialize thread-local alloc buffer related fields
1758 this->initialize_tlab();
1759
1760 // used to test validity of stack trace backs
1761 this->record_base_of_stack_pointer();
1762
1763 this->create_stack_guard_pages();
1764
1765 this->cache_global_variables();
1766
1767 // Thread is now sufficient initialized to be handled by the safepoint code as being
1768 // in the VM. Change thread state from _thread_new to _thread_in_vm
1769 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1770
1771 assert(JavaThread::current() == this, "sanity check");
1772 assert(!Thread::current()->owns_locks(), "sanity check");
1773
1774 DTRACE_THREAD_PROBE(start, this);
1775
1776 // This operation might block. We call that after all safepoint checks for a new thread has
1777 // been completed.
1778 this->set_active_handles(JNIHandleBlock::allocate_block());
1779
1780 if (JvmtiExport::should_post_thread_life()) {
1781 JvmtiExport::post_thread_start(this);
1782
1783 }
1784
1785 // We call another function to do the rest so we are sure that the stack addresses used
1786 // from there will be lower than the stack base just computed
1787 thread_main_inner();
1788
1789 // Note, thread is no longer valid at this point!
1790 }
1791
1792
1793 void JavaThread::thread_main_inner() {
1794 assert(JavaThread::current() == this, "sanity check");
1795 assert(this->threadObj() != NULL, "just checking");
1796
1797 // Execute thread entry point unless this thread has a pending exception
1798 // or has been stopped before starting.
1799 // Note: Due to JVM_StopThread we can have pending exceptions already!
1800 if (!this->has_pending_exception() &&
1801 !java_lang_Thread::is_stillborn(this->threadObj())) {
1802 {
1803 ResourceMark rm(this);
1804 this->set_native_thread_name(this->get_thread_name());
1805 }
1806 HandleMark hm(this);
1807 this->entry_point()(this, this);
1808 }
1809
1810 DTRACE_THREAD_PROBE(stop, this);
1811
1812 this->exit(false);
1813 this->smr_delete();
1814 }
1815
1816
1817 static void ensure_join(JavaThread* thread) {
1818 // We do not need to grab the Threads_lock, since we are operating on ourself.
1819 Handle threadObj(thread, thread->threadObj());
1820 assert(threadObj.not_null(), "java thread object must exist");
1821 ObjectLocker lock(threadObj, thread);
1822 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1823 thread->clear_pending_exception();
1824 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
1825 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1826 // Clear the native thread instance - this makes isAlive return false and allows the join()
1827 // to complete once we've done the notify_all below
1828 java_lang_Thread::set_thread(threadObj(), NULL);
1829 lock.notify_all(thread);
1830 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1831 thread->clear_pending_exception();
1832 }
1833
1834 static bool is_daemon(oop threadObj) {
1835 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
239 // This initial value ==> never claimed.
240 _oops_do_parity = 0;
241 _threads_hazard_ptr = NULL;
350 #ifdef SOLARIS
351 if (os::is_primordial_thread()) {
352 os::Solaris::correct_stack_boundaries_for_primordial_thread(this);
353 }
354 #endif
355
356 // Set stack limits after thread is initialized.
357 if (is_Java_thread()) {
358 ((JavaThread*) this)->set_stack_overflow_limit();
359 ((JavaThread*) this)->set_reserved_stack_activation(stack_base());
360 }
361 }
362
363 #if INCLUDE_NMT
364 void Thread::register_thread_stack_with_NMT() {
365 MemTracker::record_thread_stack(stack_end(), stack_size());
366 }
367 #endif // INCLUDE_NMT
368
369 void Thread::call_run() {
370 DEBUG_ONLY(_run_state = CALL_RUN;)
371
372 // At this point, Thread object should be fully initialized and
373 // Thread::current() should be set.
374
375 assert(Thread::current_or_null() != NULL, "current thread is unset");
376 assert(Thread::current_or_null() == this, "current thread is wrong");
377
378 // Perform common initialization actions
379
380 register_thread_stack_with_NMT();
381
382 JFR_ONLY(Jfr::on_thread_start(this);)
383
384 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
385 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
386 os::current_thread_id(), p2i(stack_base() - stack_size()),
387 p2i(stack_base()), stack_size()/1024);
388
389 // Perform <ChildClass> initialization actions
390 DEBUG_ONLY(_run_state = PRE_RUN;)
391 this->pre_run();
392
393 // Invoke <ChildClass>::run()
394 DEBUG_ONLY(_run_state = RUN;)
395 this->run();
396 // Returned from <ChildClass>::run(). Thread finished.
397
398 // Perform common tear-down actions
399
400 assert(Thread::current_or_null() != NULL, "current thread is unset");
401 assert(Thread::current_or_null() == this, "current thread is wrong");
402
403 // Perform <ChildClass> tear-down actions
404 DEBUG_ONLY(_run_state = POST_RUN;)
405 this->post_run();
406
407 // Note: at this point the thread object may already have deleted itself,
408 // so from here on do not dereference *this*. Not all thread types currently
409 // delete themselves when they terminate. But no thread should ever be deleted
410 // asynchronously with respect to its termination - that is what _run_state can
411 // be used to check.
412
413 assert(Thread::current_or_null() == NULL, "current thread still present");
414 }
415
416 Thread::~Thread() {
417
418 // Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually
419 // get started due to errors etc. Any active thread should at least reach post_run
420 // before it is deleted (usually in post_run()).
421 assert(_run_state == PRE_CALL_RUN ||
422 _run_state == POST_RUN, "Active Thread deleted before post_run()");
423
424 // Notify the barrier set that a thread is being destroyed. Note that a barrier
425 // set might not be available if we encountered errors during bootstrapping.
426 BarrierSet* const barrier_set = BarrierSet::barrier_set();
427 if (barrier_set != NULL) {
428 barrier_set->on_thread_destroy(this);
429 }
430
431 // stack_base can be NULL if the thread is never started or exited before
432 // record_stack_base_and_size called. Although, we would like to ensure
433 // that all started threads do call record_stack_base_and_size(), there is
434 // not proper way to enforce that.
435 #if INCLUDE_NMT
436 if (_stack_base != NULL) {
437 MemTracker::release_thread_stack(stack_end(), stack_size());
438 #ifdef ASSERT
439 set_stack_base(NULL);
440 #endif
441 }
442 #endif // INCLUDE_NMT
443
450 assert(last_handle_mark() == NULL, "check we have reached the end");
451
452 // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
453 // We NULL out the fields for good hygiene.
454 ParkEvent::Release(_ParkEvent); _ParkEvent = NULL;
455 ParkEvent::Release(_SleepEvent); _SleepEvent = NULL;
456 ParkEvent::Release(_MutexEvent); _MutexEvent = NULL;
457 ParkEvent::Release(_MuxEvent); _MuxEvent = NULL;
458
459 delete handle_area();
460 delete metadata_handles();
461
462 // SR_handler uses this as a termination indicator -
463 // needs to happen before os::free_thread()
464 delete _SR_lock;
465 _SR_lock = NULL;
466
467 // osthread() can be NULL, if creation of thread failed.
468 if (osthread() != NULL) os::free_thread(osthread());
469
470 // Clear Thread::current if thread is deleting itself and it has not
471 // already been done. This must be done before the memory is deallocated.
472 // Needed to ensure JNI correctly detects non-attached threads.
473 if (this == Thread::current_or_null()) {
474 Thread::clear_thread_current();
475 }
476
477 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
478 }
479
480 #ifdef ASSERT
481 // A JavaThread is considered "dangling" if it is not the current
482 // thread, has been added the Threads list, the system is not at a
483 // safepoint and the Thread is not "protected".
484 //
485 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
486 assert(!thread->is_Java_thread() || Thread::current() == thread ||
487 !((JavaThread *) thread)->on_thread_list() ||
488 SafepointSynchronize::is_at_safepoint() ||
489 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
490 "possibility of dangling Thread pointer");
491 }
492 #endif
493
1057 }
1058
1059 bool Thread::is_in_usable_stack(address adr) const {
1060 size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0;
1061 size_t usable_stack_size = _stack_size - stack_guard_size;
1062
1063 return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
1064 }
1065
1066
1067 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
1068 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
1069 // used for compilation in the future. If that change is made, the need for these methods
1070 // should be revisited, and they should be removed if possible.
1071
1072 bool Thread::is_lock_owned(address adr) const {
1073 return on_local_stack(adr);
1074 }
1075
1076 bool Thread::set_as_starting_thread() {
1077 assert(_starting_thread == NULL, "already initialized");
1078 // NOTE: this must be called inside the main thread.
1079 DEBUG_ONLY(_starting_thread = this;)
1080 return os::create_main_thread((JavaThread*)this);
1081 }
1082
1083 static void initialize_class(Symbol* class_name, TRAPS) {
1084 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
1085 InstanceKlass::cast(klass)->initialize(CHECK);
1086 }
1087
1088
1089 // Creates the initial ThreadGroup
1090 static Handle create_initial_thread_group(TRAPS) {
1091 Handle system_instance = JavaCalls::construct_new_instance(
1092 SystemDictionary::ThreadGroup_klass(),
1093 vmSymbols::void_method_signature(),
1094 CHECK_NH);
1095 Universe::set_system_thread_group(system_instance());
1096
1097 Handle string = java_lang_String::create_from_str("main", CHECK_NH);
1098 Handle main_instance = JavaCalls::construct_new_instance(
1099 SystemDictionary::ThreadGroup_klass(),
1261
1262 List() : _head(NULL), _protect() {}
1263 };
1264
1265 NonJavaThread::List NonJavaThread::_the_list;
1266
1267 NonJavaThread::Iterator::Iterator() :
1268 _protect_enter(_the_list._protect.enter()),
1269 _current(OrderAccess::load_acquire(&_the_list._head))
1270 {}
1271
1272 NonJavaThread::Iterator::~Iterator() {
1273 _the_list._protect.exit(_protect_enter);
1274 }
1275
1276 void NonJavaThread::Iterator::step() {
1277 assert(!end(), "precondition");
1278 _current = OrderAccess::load_acquire(&_current->_next);
1279 }
1280
1281 // _next == this is used to indicate not yet in list.
1282 NonJavaThread::NonJavaThread() : Thread(), _next(this) {
1283 // During bootstrap, before barrier set creation, record threads in
1284 // the list so barrier set creation can find them.
1285 if (BarrierSet::barrier_set() == NULL) {
1286 assert(Thread::current_or_null() == _starting_thread,
1287 "only the main thread should create other threads during startup");
1288 add_to_the_list();
1289 }
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 // Add to the list if not already present. During startup
1316 // threads will be added at construction time.
1317 if (_next == this) {
1318 assert(BarrierSet::barrier_set() != NULL, "invariant");
1319 add_to_the_list();
1320 }
1321 // This is slightly odd in that NamedThread is a subclass, but
1322 // in fact name() is defined in Thread
1323 assert(this->name() != NULL, "thread name was not set before it was started");
1324 this->set_native_thread_name(this->name());
1325 }
1326
1327 void NonJavaThread::post_run() {
1328 JFR_ONLY(Jfr::on_thread_exit(this);)
1329 remove_from_the_list();
1330 // Ensure thread-local-storage is cleared before termination.
1331 Thread::clear_thread_current();
1332 }
1333
1334 // NamedThread -- non-JavaThread subclasses with multiple
1335 // uniquely named instances should derive from this.
1336 NamedThread::NamedThread() :
1337 NonJavaThread(),
1338 _name(NULL),
1339 _processed_thread(NULL),
1340 _gc_id(GCId::undefined())
1341 {}
1342
1343 NamedThread::~NamedThread() {
1344 if (_name != NULL) {
1345 FREE_C_HEAP_ARRAY(char, _name);
1346 _name = NULL;
1347 }
1348 }
1349
1350 void NamedThread::set_name(const char* format, ...) {
1351 guarantee(_name == NULL, "Only get to set name once.");
1352 _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1353 guarantee(_name != NULL, "alloc failure");
1354 va_list ap;
1355 va_start(ap, format);
1356 jio_vsnprintf(_name, max_name_len, format, ap);
1357 va_end(ap);
1358 }
1359
1360 void NamedThread::print_on(outputStream* st) const {
1361 st->print("\"%s\" ", name());
1362 Thread::print_on(st);
1363 st->cr();
1364 }
1365
1366
1367 // ======= WatcherThread ========
1368
1369 // The watcher thread exists to simulate timer interrupts. It should
1370 // be replaced by an abstraction over whatever native support for
1371 // timer interrupts exists on the platform.
1372
1373 WatcherThread* WatcherThread::_watcher_thread = NULL;
1374 bool WatcherThread::_startable = false;
1375 volatile bool WatcherThread::_should_terminate = false;
1376
1377 WatcherThread::WatcherThread() : NonJavaThread() {
1378 assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1379 if (os::create_thread(this, os::watcher_thread)) {
1436
1437 remaining = PeriodicTask::time_to_wait();
1438 if (remaining == 0) {
1439 // Last task was just disenrolled so loop around and wait until
1440 // another task gets enrolled
1441 continue;
1442 }
1443
1444 remaining -= time_slept;
1445 if (remaining <= 0) {
1446 break;
1447 }
1448 }
1449
1450 return time_slept;
1451 }
1452
1453 void WatcherThread::run() {
1454 assert(this == watcher_thread(), "just checking");
1455
1456 this->set_active_handles(JNIHandleBlock::allocate_block());
1457 while (true) {
1458 assert(watcher_thread() == Thread::current(), "thread consistency check");
1459 assert(watcher_thread() == this, "thread consistency check");
1460
1461 // Calculate how long it'll be until the next PeriodicTask work
1462 // should be done, and sleep that amount of time.
1463 int time_waited = sleep();
1464
1465 if (VMError::is_error_reported()) {
1466 // A fatal error has happened, the error handler(VMError::report_and_die)
1467 // should abort JVM after creating an error log file. However in some
1468 // rare cases, the error handler itself might deadlock. Here periodically
1469 // check for error reporting timeouts, and if it happens, just proceed to
1470 // abort the VM.
1471
1472 // This code is in WatcherThread because WatcherThread wakes up
1473 // periodically so the fatal error handler doesn't need to do anything;
1474 // also because the WatcherThread is less likely to crash than other
1475 // threads.
1791 delete deferred;
1792 }
1793
1794 // All Java related clean up happens in exit
1795 ThreadSafepointState::destroy(this);
1796 if (_thread_stat != NULL) delete _thread_stat;
1797
1798 #if INCLUDE_JVMCI
1799 if (JVMCICounterSize > 0) {
1800 if (jvmci_counters_include(this)) {
1801 for (int i = 0; i < JVMCICounterSize; i++) {
1802 _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1803 }
1804 }
1805 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1806 }
1807 #endif // INCLUDE_JVMCI
1808 }
1809
1810
1811 // First JavaThread specific code executed by a new Java thread.
1812 void JavaThread::pre_run() {
1813 // empty - see comments in run()
1814 }
1815
1816 // The main routine called by a new Java thread. This isn't overridden
1817 // by subclasses, instead different subclasses define a different "entry_point"
1818 // which defines the actual logic for that kind of thread.
1819 void JavaThread::run() {
1820 // initialize thread-local alloc buffer related fields
1821 this->initialize_tlab();
1822
1823 // Used to test validity of stack trace backs.
1824 // This can't be moved into pre_run() else we invalidate
1825 // the requirement that thread_main_inner is lower on
1826 // the stack. Consequently all the initialization logic
1827 // stays here in run() rather than pre_run().
1828 this->record_base_of_stack_pointer();
1829
1830 this->create_stack_guard_pages();
1831
1832 this->cache_global_variables();
1833
1834 // Thread is now sufficiently initialized to be handled by the safepoint code as being
1835 // in the VM. Change thread state from _thread_new to _thread_in_vm
1836 ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1837
1838 assert(JavaThread::current() == this, "sanity check");
1839 assert(!Thread::current()->owns_locks(), "sanity check");
1840
1841 DTRACE_THREAD_PROBE(start, this);
1842
1843 // This operation might block. We call that after all safepoint checks for a new thread has
1844 // been completed.
1845 this->set_active_handles(JNIHandleBlock::allocate_block());
1846
1847 if (JvmtiExport::should_post_thread_life()) {
1848 JvmtiExport::post_thread_start(this);
1849
1850 }
1851
1852 // We call another function to do the rest so we are sure that the stack addresses used
1853 // from there will be lower than the stack base just computed.
1854 thread_main_inner();
1855 }
1856
1857 void JavaThread::thread_main_inner() {
1858 assert(JavaThread::current() == this, "sanity check");
1859 assert(this->threadObj() != NULL, "just checking");
1860
1861 // Execute thread entry point unless this thread has a pending exception
1862 // or has been stopped before starting.
1863 // Note: Due to JVM_StopThread we can have pending exceptions already!
1864 if (!this->has_pending_exception() &&
1865 !java_lang_Thread::is_stillborn(this->threadObj())) {
1866 {
1867 ResourceMark rm(this);
1868 this->set_native_thread_name(this->get_thread_name());
1869 }
1870 HandleMark hm(this);
1871 this->entry_point()(this, this);
1872 }
1873
1874 DTRACE_THREAD_PROBE(stop, this);
1875
1876 this->exit(false);
1877 }
1878
1879 // Shared teardown for all JavaThreads
1880 void JavaThread::post_run() {
1881 // Defer deletion to here to ensure 'this' is still referenceable in call_run
1882 // for any shared tear-down.
1883 this->smr_delete();
1884 }
1885
1886 static void ensure_join(JavaThread* thread) {
1887 // We do not need to grab the Threads_lock, since we are operating on ourself.
1888 Handle threadObj(thread, thread->threadObj());
1889 assert(threadObj.not_null(), "java thread object must exist");
1890 ObjectLocker lock(threadObj, thread);
1891 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1892 thread->clear_pending_exception();
1893 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED.
1894 java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1895 // Clear the native thread instance - this makes isAlive return false and allows the join()
1896 // to complete once we've done the notify_all below
1897 java_lang_Thread::set_thread(threadObj(), NULL);
1898 lock.notify_all(thread);
1899 // Ignore pending exception (ThreadDeath), since we are exiting anyway
1900 thread->clear_pending_exception();
1901 }
1902
1903 static bool is_daemon(oop threadObj) {
1904 return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj));
|