src/hotspot/share/runtime/thread.cpp
changeset 48105 8d15b1369c7a
parent 48005 9fd89aabb6cd
child 48173 cb63f08dad03
equal deleted inserted replaced
48096:513e0b467a92 48105:8d15b1369c7a
    69 #include "runtime/init.hpp"
    69 #include "runtime/init.hpp"
    70 #include "runtime/interfaceSupport.hpp"
    70 #include "runtime/interfaceSupport.hpp"
    71 #include "runtime/java.hpp"
    71 #include "runtime/java.hpp"
    72 #include "runtime/javaCalls.hpp"
    72 #include "runtime/javaCalls.hpp"
    73 #include "runtime/jniPeriodicChecker.hpp"
    73 #include "runtime/jniPeriodicChecker.hpp"
    74 #include "runtime/timerTrace.hpp"
       
    75 #include "runtime/memprofiler.hpp"
    74 #include "runtime/memprofiler.hpp"
    76 #include "runtime/mutexLocker.hpp"
    75 #include "runtime/mutexLocker.hpp"
    77 #include "runtime/objectMonitor.hpp"
    76 #include "runtime/objectMonitor.hpp"
    78 #include "runtime/orderAccess.inline.hpp"
    77 #include "runtime/orderAccess.inline.hpp"
    79 #include "runtime/osThread.hpp"
    78 #include "runtime/osThread.hpp"
       
    79 #include "runtime/prefetch.inline.hpp"
    80 #include "runtime/safepoint.hpp"
    80 #include "runtime/safepoint.hpp"
    81 #include "runtime/safepointMechanism.inline.hpp"
    81 #include "runtime/safepointMechanism.inline.hpp"
    82 #include "runtime/sharedRuntime.hpp"
    82 #include "runtime/sharedRuntime.hpp"
    83 #include "runtime/statSampler.hpp"
    83 #include "runtime/statSampler.hpp"
    84 #include "runtime/stubRoutines.hpp"
    84 #include "runtime/stubRoutines.hpp"
    85 #include "runtime/sweeper.hpp"
    85 #include "runtime/sweeper.hpp"
    86 #include "runtime/task.hpp"
    86 #include "runtime/task.hpp"
    87 #include "runtime/thread.inline.hpp"
    87 #include "runtime/thread.inline.hpp"
    88 #include "runtime/threadCritical.hpp"
    88 #include "runtime/threadCritical.hpp"
       
    89 #include "runtime/threadSMR.inline.hpp"
       
    90 #include "runtime/timer.hpp"
       
    91 #include "runtime/timerTrace.hpp"
    89 #include "runtime/vframe.hpp"
    92 #include "runtime/vframe.hpp"
    90 #include "runtime/vframeArray.hpp"
    93 #include "runtime/vframeArray.hpp"
    91 #include "runtime/vframe_hp.hpp"
    94 #include "runtime/vframe_hp.hpp"
    92 #include "runtime/vmThread.hpp"
    95 #include "runtime/vmThread.hpp"
    93 #include "runtime/vm_operations.hpp"
    96 #include "runtime/vm_operations.hpp"
   102 #include "utilities/defaultStream.hpp"
   105 #include "utilities/defaultStream.hpp"
   103 #include "utilities/dtrace.hpp"
   106 #include "utilities/dtrace.hpp"
   104 #include "utilities/events.hpp"
   107 #include "utilities/events.hpp"
   105 #include "utilities/macros.hpp"
   108 #include "utilities/macros.hpp"
   106 #include "utilities/preserveException.hpp"
   109 #include "utilities/preserveException.hpp"
       
   110 #include "utilities/resourceHash.hpp"
   107 #include "utilities/vmError.hpp"
   111 #include "utilities/vmError.hpp"
   108 #if INCLUDE_ALL_GCS
   112 #if INCLUDE_ALL_GCS
   109 #include "gc/cms/concurrentMarkSweepThread.hpp"
   113 #include "gc/cms/concurrentMarkSweepThread.hpp"
   110 #include "gc/g1/concurrentMarkThread.inline.hpp"
   114 #include "gc/g1/concurrentMarkThread.inline.hpp"
   111 #include "gc/parallel/pcTasks.hpp"
   115 #include "gc/parallel/pcTasks.hpp"
   193   }
   197   }
   194 }
   198 }
   195 
   199 
   196 void Thread::operator delete(void* p) {
   200 void Thread::operator delete(void* p) {
   197   if (UseBiasedLocking) {
   201   if (UseBiasedLocking) {
   198     void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
   202     FreeHeap(((Thread*) p)->_real_malloc_address);
   199     FreeHeap(real_malloc_addr);
       
   200   } else {
   203   } else {
   201     FreeHeap(p);
   204     FreeHeap(p);
   202   }
   205   }
   203 }
   206 }
   204 
   207 
       
   208 void JavaThread::smr_delete() {
       
   209   if (_on_thread_list) {
       
   210     Threads::smr_delete(this);
       
   211   } else {
       
   212     delete this;
       
   213   }
       
   214 }
   205 
   215 
   206 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
   216 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
   207 // JavaThread
   217 // JavaThread
   208 
   218 
   209 
   219 
   225   set_free_handle_block(NULL);
   235   set_free_handle_block(NULL);
   226   set_last_handle_mark(NULL);
   236   set_last_handle_mark(NULL);
   227 
   237 
   228   // This initial value ==> never claimed.
   238   // This initial value ==> never claimed.
   229   _oops_do_parity = 0;
   239   _oops_do_parity = 0;
       
   240   _threads_hazard_ptr = NULL;
       
   241   _nested_threads_hazard_ptr = NULL;
       
   242   _nested_threads_hazard_ptr_cnt = 0;
   230 
   243 
   231   // the handle mark links itself to last_handle_mark
   244   // the handle mark links itself to last_handle_mark
   232   new HandleMark(this);
   245   new HandleMark(this);
   233 
   246 
   234   // plain initialization
   247   // plain initialization
   396 void Thread::run() {
   409 void Thread::run() {
   397   ShouldNotReachHere();
   410   ShouldNotReachHere();
   398 }
   411 }
   399 
   412 
   400 #ifdef ASSERT
   413 #ifdef ASSERT
   401 // Private method to check for dangling thread pointer
   414 // A JavaThread is considered "dangling" if it is not the current
   402 void check_for_dangling_thread_pointer(Thread *thread) {
   415 // thread, has been added the Threads list, the system is not at a
   403   assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
   416 // safepoint and the Thread is not "protected".
       
   417 //
       
   418 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
       
   419   assert(!thread->is_Java_thread() || Thread::current() == thread ||
       
   420          !((JavaThread *) thread)->on_thread_list() ||
       
   421          SafepointSynchronize::is_at_safepoint() ||
       
   422          Threads::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
   404          "possibility of dangling Thread pointer");
   423          "possibility of dangling Thread pointer");
   405 }
   424 }
   406 #endif
   425 #endif
   407 
   426 
   408 ThreadPriority Thread::get_priority(const Thread* const thread) {
   427 ThreadPriority Thread::get_priority(const Thread* const thread) {
   730   // thread did not suspend after all our retries
   749   // thread did not suspend after all our retries
   731   *bits |= 0x00200000;
   750   *bits |= 0x00200000;
   732   return false;
   751   return false;
   733 }
   752 }
   734 
   753 
       
   754 // Called from API entry points which perform stack walking. If the
       
   755 // associated JavaThread is the current thread, then wait_for_suspend
       
   756 // is not used. Otherwise, it determines if we should wait for the
       
   757 // "other" thread to complete external suspension. (NOTE: in future
       
   758 // releases the suspension mechanism should be reimplemented so this
       
   759 // is not necessary.)
       
   760 //
       
   761 bool
       
   762 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) {
       
   763   if (this != JavaThread::current()) {
       
   764     // "other" threads require special handling.
       
   765     if (wait_for_suspend) {
       
   766       // We are allowed to wait for the external suspend to complete
       
   767       // so give the other thread a chance to get suspended.
       
   768       if (!wait_for_ext_suspend_completion(SuspendRetryCount,
       
   769                                            SuspendRetryDelay, bits)) {
       
   770         // Didn't make it so let the caller know.
       
   771         return false;
       
   772       }
       
   773     }
       
   774     // We aren't allowed to wait for the external suspend to complete
       
   775     // so if the other thread isn't externally suspended we need to
       
   776     // let the caller know.
       
   777     else if (!is_ext_suspend_completed_with_lock(bits)) {
       
   778       return false;
       
   779     }
       
   780   }
       
   781 
       
   782   return true;
       
   783 }
       
   784 
   735 #ifndef PRODUCT
   785 #ifndef PRODUCT
   736 void JavaThread::record_jump(address target, address instr, const char* file,
   786 void JavaThread::record_jump(address target, address instr, const char* file,
   737                              int line) {
   787                              int line) {
   738 
   788 
   739   // This should not need to be atomic as the only way for simultaneous
   789   // This should not need to be atomic as the only way for simultaneous
   808     }
   858     }
   809     st->print("tid=" INTPTR_FORMAT " ", p2i(this));
   859     st->print("tid=" INTPTR_FORMAT " ", p2i(this));
   810     ext().print_on(st);
   860     ext().print_on(st);
   811     osthread()->print_on(st);
   861     osthread()->print_on(st);
   812   }
   862   }
       
   863   if (_threads_hazard_ptr != NULL) {
       
   864     st->print("_threads_hazard_ptr=" INTPTR_FORMAT, p2i(_threads_hazard_ptr));
       
   865   }
       
   866   if (_nested_threads_hazard_ptr != NULL) {
       
   867     print_nested_threads_hazard_ptrs_on(st);
       
   868   }
       
   869   st->print(" ");
   813   debug_only(if (WizardMode) print_owned_locks_on(st);)
   870   debug_only(if (WizardMode) print_owned_locks_on(st);)
       
   871 }
       
   872 
       
   873 void Thread::print_nested_threads_hazard_ptrs_on(outputStream* st) const {
       
   874   assert(_nested_threads_hazard_ptr != NULL, "must be set to print");
       
   875 
       
   876   if (EnableThreadSMRStatistics) {
       
   877     st->print(", _nested_threads_hazard_ptr_cnt=%u", _nested_threads_hazard_ptr_cnt);
       
   878   }
       
   879   st->print(", _nested_threads_hazard_ptrs=");
       
   880   for (NestedThreadsList* node = _nested_threads_hazard_ptr; node != NULL;
       
   881        node = node->next()) {
       
   882     if (node != _nested_threads_hazard_ptr) {
       
   883       // First node does not need a comma-space separator.
       
   884       st->print(", ");
       
   885     }
       
   886     st->print(INTPTR_FORMAT, p2i(node->t_list()));
       
   887   }
   814 }
   888 }
   815 
   889 
   816 // Thread::print_on_error() is called by fatal error handler. Don't use
   890 // Thread::print_on_error() is called by fatal error handler. Don't use
   817 // any lock or allocate memory.
   891 // any lock or allocate memory.
   818 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
   892 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
   831   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
   905   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
   832             p2i(stack_end()), p2i(stack_base()));
   906             p2i(stack_end()), p2i(stack_base()));
   833 
   907 
   834   if (osthread()) {
   908   if (osthread()) {
   835     st->print(" [id=%d]", osthread()->thread_id());
   909     st->print(" [id=%d]", osthread()->thread_id());
       
   910   }
       
   911 
       
   912   if (_threads_hazard_ptr != NULL) {
       
   913     st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_threads_hazard_ptr));
       
   914   }
       
   915   if (_nested_threads_hazard_ptr != NULL) {
       
   916     print_nested_threads_hazard_ptrs_on(st);
   836   }
   917   }
   837 }
   918 }
   838 
   919 
   839 void Thread::print_value_on(outputStream* st) const {
   920 void Thread::print_value_on(outputStream* st) const {
   840   if (is_Named_thread()) {
   921   if (is_Named_thread()) {
   869 
   950 
   870 #endif
   951 #endif
   871 
   952 
   872 #ifndef PRODUCT
   953 #ifndef PRODUCT
   873 
   954 
   874 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
   955 // The flag: potential_vm_operation notifies if this particular safepoint state could potentially
   875 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
   956 // invoke the vm-thread (e.g., an oop allocation). In that case, we also have to make sure that
   876 // no threads which allow_vm_block's are held
   957 // no threads which allow_vm_block's are held
   877 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
   958 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
   878   // Check if current thread is allowed to block at a safepoint
   959   // Check if current thread is allowed to block at a safepoint
   879   if (!(_allow_safepoint_count == 0)) {
   960   if (!(_allow_safepoint_count == 0)) {
   880     fatal("Possible safepoint reached by thread that does not allow it");
   961     fatal("Possible safepoint reached by thread that does not allow it");
  1397 }
  1478 }
  1398 
  1479 
  1399 void JavaThread::collect_counters(typeArrayOop array) {
  1480 void JavaThread::collect_counters(typeArrayOop array) {
  1400   if (JVMCICounterSize > 0) {
  1481   if (JVMCICounterSize > 0) {
  1401     MutexLocker tl(Threads_lock);
  1482     MutexLocker tl(Threads_lock);
       
  1483     JavaThreadIteratorWithHandle jtiwh;
  1402     for (int i = 0; i < array->length(); i++) {
  1484     for (int i = 0; i < array->length(); i++) {
  1403       array->long_at_put(i, _jvmci_old_thread_counters[i]);
  1485       array->long_at_put(i, _jvmci_old_thread_counters[i]);
  1404     }
  1486     }
  1405     for (JavaThread* tp = Threads::first(); tp != NULL; tp = tp->next()) {
  1487     for (; JavaThread *tp = jtiwh.next(); ) {
  1406       if (jvmci_counters_include(tp)) {
  1488       if (jvmci_counters_include(tp)) {
  1407         for (int i = 0; i < array->length(); i++) {
  1489         for (int i = 0; i < array->length(); i++) {
  1408           array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]);
  1490           array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]);
  1409         }
  1491         }
  1410       }
  1492       }
  1433   set_deopt_mark(NULL);
  1515   set_deopt_mark(NULL);
  1434   set_deopt_compiled_method(NULL);
  1516   set_deopt_compiled_method(NULL);
  1435   clear_must_deopt_id();
  1517   clear_must_deopt_id();
  1436   set_monitor_chunks(NULL);
  1518   set_monitor_chunks(NULL);
  1437   set_next(NULL);
  1519   set_next(NULL);
       
  1520   _on_thread_list = false;
  1438   set_thread_state(_thread_new);
  1521   set_thread_state(_thread_new);
  1439   _terminated = _not_terminated;
  1522   _terminated = _not_terminated;
  1440   _privileged_stack_top = NULL;
  1523   _privileged_stack_top = NULL;
  1441   _array_for_gc = NULL;
  1524   _array_for_gc = NULL;
  1442   _suspend_equivalent = false;
  1525   _suspend_equivalent = false;
  1713   }
  1796   }
  1714 
  1797 
  1715   DTRACE_THREAD_PROBE(stop, this);
  1798   DTRACE_THREAD_PROBE(stop, this);
  1716 
  1799 
  1717   this->exit(false);
  1800   this->exit(false);
  1718   delete this;
  1801   this->smr_delete();
  1719 }
  1802 }
  1720 
  1803 
  1721 
  1804 
  1722 static void ensure_join(JavaThread* thread) {
  1805 static void ensure_join(JavaThread* thread) {
  1723   // We do not need to grap the Threads_lock, since we are operating on ourself.
  1806   // We do not need to grab the Threads_lock, since we are operating on ourself.
  1724   Handle threadObj(thread, thread->threadObj());
  1807   Handle threadObj(thread, thread->threadObj());
  1725   assert(threadObj.not_null(), "java thread object must exist");
  1808   assert(threadObj.not_null(), "java thread object must exist");
  1726   ObjectLocker lock(threadObj, thread);
  1809   ObjectLocker lock(threadObj, thread);
  1727   // Ignore pending exception (ThreadDeath), since we are exiting anyway
  1810   // Ignore pending exception (ThreadDeath), since we are exiting anyway
  1728   thread->clear_pending_exception();
  1811   thread->clear_pending_exception();
  1739 
  1822 
  1740 // For any new cleanup additions, please check to see if they need to be applied to
  1823 // For any new cleanup additions, please check to see if they need to be applied to
  1741 // cleanup_failed_attach_current_thread as well.
  1824 // cleanup_failed_attach_current_thread as well.
  1742 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
  1825 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
  1743   assert(this == JavaThread::current(), "thread consistency check");
  1826   assert(this == JavaThread::current(), "thread consistency check");
       
  1827 
       
  1828   elapsedTimer _timer_exit_phase1;
       
  1829   elapsedTimer _timer_exit_phase2;
       
  1830   elapsedTimer _timer_exit_phase3;
       
  1831   elapsedTimer _timer_exit_phase4;
       
  1832 
       
  1833   if (log_is_enabled(Debug, os, thread, timer)) {
       
  1834     _timer_exit_phase1.start();
       
  1835   }
  1744 
  1836 
  1745   HandleMark hm(this);
  1837   HandleMark hm(this);
  1746   Handle uncaught_exception(this, this->pending_exception());
  1838   Handle uncaught_exception(this, this->pending_exception());
  1747   this->clear_pending_exception();
  1839   this->clear_pending_exception();
  1748   Handle threadObj(this, this->threadObj());
  1840   Handle threadObj(this, this->threadObj());
  1839     // no more external suspends are allowed at this point
  1931     // no more external suspends are allowed at this point
  1840   } else {
  1932   } else {
  1841     // before_exit() has already posted JVMTI THREAD_END events
  1933     // before_exit() has already posted JVMTI THREAD_END events
  1842   }
  1934   }
  1843 
  1935 
       
  1936   if (log_is_enabled(Debug, os, thread, timer)) {
       
  1937     _timer_exit_phase1.stop();
       
  1938     _timer_exit_phase2.start();
       
  1939   }
  1844   // Notify waiters on thread object. This has to be done after exit() is called
  1940   // Notify waiters on thread object. This has to be done after exit() is called
  1845   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
  1941   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
  1846   // group should have the destroyed bit set before waiters are notified).
  1942   // group should have the destroyed bit set before waiters are notified).
  1847   ensure_join(this);
  1943   ensure_join(this);
  1848   assert(!this->has_pending_exception(), "ensure_join should have cleared");
  1944   assert(!this->has_pending_exception(), "ensure_join should have cleared");
  1849 
  1945 
       
  1946   if (log_is_enabled(Debug, os, thread, timer)) {
       
  1947     _timer_exit_phase2.stop();
       
  1948     _timer_exit_phase3.start();
       
  1949   }
  1850   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
  1950   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
  1851   // held by this thread must be released. The spec does not distinguish
  1951   // held by this thread must be released. The spec does not distinguish
  1852   // between JNI-acquired and regular Java monitors. We can only see
  1952   // between JNI-acquired and regular Java monitors. We can only see
  1853   // regular Java monitors here if monitor enter-exit matching is broken.
  1953   // regular Java monitors here if monitor enter-exit matching is broken.
  1854   //
  1954   //
  1912 
  2012 
  1913   log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
  2013   log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
  1914     exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
  2014     exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
  1915     os::current_thread_id());
  2015     os::current_thread_id());
  1916 
  2016 
       
  2017   if (log_is_enabled(Debug, os, thread, timer)) {
       
  2018     _timer_exit_phase3.stop();
       
  2019     _timer_exit_phase4.start();
       
  2020   }
  1917   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
  2021   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
  1918   Threads::remove(this);
  2022   Threads::remove(this);
  1919 
  2023 
  1920   // If someone set a handshake on us just as we entered exit path, we simple cancel it.
  2024   if (log_is_enabled(Debug, os, thread, timer)) {
  1921   if (ThreadLocalHandshakes) {
  2025     _timer_exit_phase4.stop();
  1922     cancel_handshake();
  2026     ResourceMark rm(this);
       
  2027     log_debug(os, thread, timer)("name='%s'"
       
  2028                                  ", exit-phase1=" JLONG_FORMAT
       
  2029                                  ", exit-phase2=" JLONG_FORMAT
       
  2030                                  ", exit-phase3=" JLONG_FORMAT
       
  2031                                  ", exit-phase4=" JLONG_FORMAT,
       
  2032                                  get_thread_name(),
       
  2033                                  _timer_exit_phase1.milliseconds(),
       
  2034                                  _timer_exit_phase2.milliseconds(),
       
  2035                                  _timer_exit_phase3.milliseconds(),
       
  2036                                  _timer_exit_phase4.milliseconds());
  1923   }
  2037   }
  1924 }
  2038 }
  1925 
  2039 
  1926 #if INCLUDE_ALL_GCS
  2040 #if INCLUDE_ALL_GCS
  1927 // Flush G1-related queues.
  2041 // Flush G1-related queues.
  1978     flush_barrier_queues();
  2092     flush_barrier_queues();
  1979   }
  2093   }
  1980 #endif // INCLUDE_ALL_GCS
  2094 #endif // INCLUDE_ALL_GCS
  1981 
  2095 
  1982   Threads::remove(this);
  2096   Threads::remove(this);
  1983   delete this;
  2097   this->smr_delete();
  1984 }
  2098 }
  1985 
  2099 
  1986 
  2100 
  1987 
  2101 
  1988 
  2102 
  2233 //   + Target thread will not execute any new bytecode (that's why we need to
  2347 //   + Target thread will not execute any new bytecode (that's why we need to
  2234 //     force a safepoint)
  2348 //     force a safepoint)
  2235 //   + Target thread will not enter any new monitors
  2349 //   + Target thread will not enter any new monitors
  2236 //
  2350 //
  2237 void JavaThread::java_suspend() {
  2351 void JavaThread::java_suspend() {
  2238   { MutexLocker mu(Threads_lock);
  2352   ThreadsListHandle tlh;
  2239     if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
  2353   if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) {
  2240       return;
  2354     return;
  2241     }
       
  2242   }
  2355   }
  2243 
  2356 
  2244   { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2357   { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2245     if (!is_external_suspend()) {
  2358     if (!is_external_suspend()) {
  2246       // a racing resume has cancelled us; bail out now
  2359       // a racing resume has cancelled us; bail out now
  2325 
  2438 
  2326 #ifdef ASSERT
  2439 #ifdef ASSERT
  2327 // verify the JavaThread has not yet been published in the Threads::list, and
  2440 // verify the JavaThread has not yet been published in the Threads::list, and
  2328 // hence doesn't need protection from concurrent access at this stage
  2441 // hence doesn't need protection from concurrent access at this stage
  2329 void JavaThread::verify_not_published() {
  2442 void JavaThread::verify_not_published() {
  2330   if (!Threads_lock->owned_by_self()) {
  2443   ThreadsListHandle tlh;
  2331     MutexLockerEx ml(Threads_lock,  Mutex::_no_safepoint_check_flag);
  2444   assert(!tlh.includes(this), "JavaThread shouldn't have been published yet!");
  2332     assert(!Threads::includes(this),
       
  2333            "java thread shouldn't have been published yet!");
       
  2334   } else {
       
  2335     assert(!Threads::includes(this),
       
  2336            "java thread shouldn't have been published yet!");
       
  2337   }
       
  2338 }
  2445 }
  2339 #endif
  2446 #endif
  2340 
  2447 
  2341 // Slow path when the native==>VM/Java barriers detect a safepoint is in
  2448 // Slow path when the native==>VM/Java barriers detect a safepoint is in
  2342 // progress or when _suspend_flags is non-zero.
  2449 // progress or when _suspend_flags is non-zero.
  2449 void JavaThread::java_resume() {
  2556 void JavaThread::java_resume() {
  2450   assert_locked_or_safepoint(Threads_lock);
  2557   assert_locked_or_safepoint(Threads_lock);
  2451 
  2558 
  2452   // Sanity check: thread is gone, has started exiting or the thread
  2559   // Sanity check: thread is gone, has started exiting or the thread
  2453   // was not externally suspended.
  2560   // was not externally suspended.
  2454   if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
  2561   ThreadsListHandle tlh;
       
  2562   if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) {
  2455     return;
  2563     return;
  2456   }
  2564   }
  2457 
  2565 
  2458   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2566   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2459 
  2567 
  2923     st->print(", id=%d", osthread()->thread_id());
  3031     st->print(", id=%d", osthread()->thread_id());
  2924   }
  3032   }
  2925   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
  3033   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
  2926             p2i(stack_end()), p2i(stack_base()));
  3034             p2i(stack_end()), p2i(stack_base()));
  2927   st->print("]");
  3035   st->print("]");
       
  3036 
       
  3037   if (_threads_hazard_ptr != NULL) {
       
  3038     st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_threads_hazard_ptr));
       
  3039   }
       
  3040   if (_nested_threads_hazard_ptr != NULL) {
       
  3041     print_nested_threads_hazard_ptrs_on(st);
       
  3042   }
  2928   return;
  3043   return;
  2929 }
  3044 }
  2930 
  3045 
  2931 // Verification
  3046 // Verification
  2932 
  3047 
  3316 
  3431 
  3317 
  3432 
  3318 // ======= Threads ========
  3433 // ======= Threads ========
  3319 
  3434 
  3320 // The Threads class links together all active threads, and provides
  3435 // The Threads class links together all active threads, and provides
  3321 // operations over all threads.  It is protected by its own Mutex
  3436 // operations over all threads. It is protected by the Threads_lock,
  3322 // lock, which is also used in other contexts to protect thread
  3437 // which is also used in other global contexts like safepointing.
  3323 // operations from having the thread being operated on from exiting
  3438 // ThreadsListHandles are used to safely perform operations on one
  3324 // and going away unexpectedly (e.g., safepoint synchronization)
  3439 // or more threads without the risk of the thread exiting during the
  3325 
  3440 // operation.
  3326 JavaThread* Threads::_thread_list = NULL;
  3441 //
  3327 int         Threads::_number_of_threads = 0;
  3442 // Note: The Threads_lock is currently more widely used than we
  3328 int         Threads::_number_of_non_daemon_threads = 0;
  3443 // would like. We are actively migrating Threads_lock uses to other
  3329 int         Threads::_return_code = 0;
  3444 // mechanisms in order to reduce Threads_lock contention.
  3330 int         Threads::_thread_claim_parity = 0;
  3445 
  3331 size_t      JavaThread::_stack_size_at_create = 0;
  3446 JavaThread*           Threads::_thread_list = NULL;
       
  3447 int                   Threads::_number_of_threads = 0;
       
  3448 int                   Threads::_number_of_non_daemon_threads = 0;
       
  3449 int                   Threads::_return_code = 0;
       
  3450 int                   Threads::_thread_claim_parity = 0;
       
  3451 size_t                JavaThread::_stack_size_at_create = 0;
       
  3452 // Safe Memory Reclamation (SMR) support:
       
  3453 Monitor*              Threads::_smr_delete_lock =
       
  3454                           new Monitor(Monitor::special, "smr_delete_lock",
       
  3455                                       false /* allow_vm_block */,
       
  3456                                       Monitor::_safepoint_check_never);
       
  3457 // The '_cnt', '_max' and '_times" fields are enabled via
       
  3458 // -XX:+EnableThreadSMRStatistics:
       
  3459 
       
  3460 // # of parallel threads in _smr_delete_lock->wait().
       
  3461 // Impl note: Hard to imagine > 64K waiting threads so this could be 16-bit,
       
  3462 // but there is no nice 16-bit _FORMAT support.
       
  3463 uint                  Threads::_smr_delete_lock_wait_cnt = 0;
       
  3464 
       
  3465 // Max # of parallel threads in _smr_delete_lock->wait().
       
  3466 // Impl note: See _smr_delete_lock_wait_cnt note.
       
  3467 uint                  Threads::_smr_delete_lock_wait_max = 0;
       
  3468 
       
  3469 // Flag to indicate when an _smr_delete_lock->notify() is needed.
       
  3470 // Impl note: See _smr_delete_lock_wait_cnt note.
       
  3471 volatile uint         Threads::_smr_delete_notify = 0;
       
  3472 
       
  3473 // # of threads deleted over VM lifetime.
       
  3474 // Impl note: Atomically incremented over VM lifetime so use unsigned for more
       
  3475 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
       
  3476 // isn't available everywhere (or is it?).
       
  3477 volatile uint         Threads::_smr_deleted_thread_cnt = 0;
       
  3478 
       
  3479 // Max time in millis to delete a thread.
       
  3480 // Impl note: 16-bit might be too small on an overloaded machine. Use
       
  3481 // unsigned since this is a time value. Set via Atomic::cmpxchg() in a
       
  3482 // loop for correctness.
       
  3483 volatile uint         Threads::_smr_deleted_thread_time_max = 0;
       
  3484 
       
  3485 // Cumulative time in millis to delete threads.
       
  3486 // Impl note: Atomically added to over VM lifetime so use unsigned for more
       
  3487 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
       
  3488 // isn't available everywhere (or is it?).
       
  3489 volatile uint         Threads::_smr_deleted_thread_times = 0;
       
  3490 
       
  3491 ThreadsList* volatile Threads::_smr_java_thread_list = new ThreadsList(0);
       
  3492 
       
  3493 // # of ThreadsLists allocated over VM lifetime.
       
  3494 // Impl note: We allocate a new ThreadsList for every thread create and
       
  3495 // every thread delete so we need a bigger type than the
       
  3496 // _smr_deleted_thread_cnt field.
       
  3497 uint64_t              Threads::_smr_java_thread_list_alloc_cnt = 1;
       
  3498 
       
  3499 // # of ThreadsLists freed over VM lifetime.
       
  3500 // Impl note: See _smr_java_thread_list_alloc_cnt note.
       
  3501 uint64_t              Threads::_smr_java_thread_list_free_cnt = 0;
       
  3502 
       
  3503 // Max size ThreadsList allocated.
       
  3504 // Impl note: Max # of threads alive at one time should fit in unsigned 32-bit.
       
  3505 uint                  Threads::_smr_java_thread_list_max = 0;
       
  3506 
       
  3507 // Max # of nested ThreadsLists for a thread.
       
  3508 // Impl note: Hard to imagine > 64K nested ThreadsLists so this could be
       
  3509 // 16-bit, but there is no nice 16-bit _FORMAT support.
       
  3510 uint                  Threads::_smr_nested_thread_list_max = 0;
       
  3511 
       
  3512 // # of ThreadsListHandles deleted over VM lifetime.
       
  3513 // Impl note: Atomically incremented over VM lifetime so use unsigned for
       
  3514 // more range. There will be fewer ThreadsListHandles than threads so
       
  3515 // unsigned 32-bit should be fine.
       
  3516 volatile uint         Threads::_smr_tlh_cnt = 0;
       
  3517 
       
  3518 // Max time in millis to delete a ThreadsListHandle.
       
  3519 // Impl note: 16-bit might be too small on an overloaded machine. Use
       
  3520 // unsigned since this is a time value. Set via Atomic::cmpxchg() in a
       
  3521 // loop for correctness.
       
  3522 volatile uint         Threads::_smr_tlh_time_max = 0;
       
  3523 
       
  3524 // Cumulative time in millis to delete ThreadsListHandles.
       
  3525 // Impl note: Atomically added to over VM lifetime so use unsigned for more
       
  3526 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
       
  3527 // isn't available everywhere (or is it?).
       
  3528 volatile uint         Threads::_smr_tlh_times = 0;
       
  3529 
       
  3530 ThreadsList*          Threads::_smr_to_delete_list = NULL;
       
  3531 
       
  3532 // # of parallel ThreadsLists on the to-delete list.
       
  3533 // Impl note: Hard to imagine > 64K ThreadsLists needing to be deleted so
       
  3534 // this could be 16-bit, but there is no nice 16-bit _FORMAT support.
       
  3535 uint                  Threads::_smr_to_delete_list_cnt = 0;
       
  3536 
       
  3537 // Max # of parallel ThreadsLists on the to-delete list.
       
  3538 // Impl note: See _smr_to_delete_list_cnt note.
       
  3539 uint                  Threads::_smr_to_delete_list_max = 0;
       
  3540 
  3332 #ifdef ASSERT
  3541 #ifdef ASSERT
  3333 bool        Threads::_vm_complete = false;
  3542 bool                  Threads::_vm_complete = false;
  3334 #endif
  3543 #endif
  3335 
  3544 
       
  3545 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) {
       
  3546   Prefetch::read((void*)addr, prefetch_interval);
       
  3547   return *addr;
       
  3548 }
       
  3549 
       
  3550 // Possibly the ugliest for loop the world has seen. C++ does not allow
       
  3551 // multiple types in the declaration section of the for loop. In this case
       
  3552 // we are only dealing with pointers and hence can cast them. It looks ugly
       
  3553 // but macros are ugly and therefore it's fine to make things absurdly ugly.
       
  3554 #define DO_JAVA_THREADS(LIST, X)                                                                                          \
       
  3555     for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes,                           \
       
  3556              *MACRO_list = (JavaThread*)(LIST),                                                                           \
       
  3557              **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(),  \
       
  3558              **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(),                                     \
       
  3559              *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval);                 \
       
  3560          MACRO_current_p != MACRO_end;                                                                                    \
       
  3561          MACRO_current_p++,                                                                                               \
       
  3562              X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval))
       
  3563 
  3336 // All JavaThreads
  3564 // All JavaThreads
  3337 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
  3565 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(get_smr_java_thread_list(), X)
  3338 
  3566 
  3339 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
  3567 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
  3340 void Threads::threads_do(ThreadClosure* tc) {
  3568 void Threads::threads_do(ThreadClosure* tc) {
  3341   assert_locked_or_safepoint(Threads_lock);
  3569   assert_locked_or_safepoint(Threads_lock);
  3342   // ALL_JAVA_THREADS iterates through all JavaThreads
  3570   // ALL_JAVA_THREADS iterates through all JavaThreads
  3433   JavaValue result(T_VOID);
  3661   JavaValue result(T_VOID);
  3434   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
  3662   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
  3435                                          vmSymbols::void_method_signature(), CHECK);
  3663                                          vmSymbols::void_method_signature(), CHECK);
  3436 }
  3664 }
  3437 
  3665 
       
  3666 // Safe Memory Reclamation (SMR) support:
       
  3667 //
       
  3668 
       
  3669 // Acquire a stable ThreadsList.
       
  3670 //
       
  3671 ThreadsList *Threads::acquire_stable_list(Thread *self, bool is_ThreadsListSetter) {
       
  3672   assert(self != NULL, "sanity check");
       
  3673   // acquire_stable_list_nested_path() will grab the Threads_lock
       
  3674   // so let's make sure the ThreadsListHandle is in a safe place.
       
  3675   // ThreadsListSetter cannot make this check on this code path.
       
  3676   debug_only(if (!is_ThreadsListSetter && StrictSafepointChecks) self->check_for_valid_safepoint_state(/* potential_vm_operation */ false);)
       
  3677 
       
  3678   if (self->get_threads_hazard_ptr() == NULL) {
       
  3679     // The typical case is first.
       
  3680     return acquire_stable_list_fast_path(self);
       
  3681   }
       
  3682 
       
  3683   // The nested case is rare.
       
  3684   return acquire_stable_list_nested_path(self);
       
  3685 }
       
  3686 
       
  3687 // Fast path (and lock free) way to acquire a stable ThreadsList.
       
  3688 //
       
  3689 ThreadsList *Threads::acquire_stable_list_fast_path(Thread *self) {
       
  3690   assert(self != NULL, "sanity check");
       
  3691   assert(self->get_threads_hazard_ptr() == NULL, "sanity check");
       
  3692   assert(self->get_nested_threads_hazard_ptr() == NULL,
       
  3693          "cannot have a nested hazard ptr with a NULL regular hazard ptr");
       
  3694 
       
  3695   ThreadsList* threads;
       
  3696 
       
  3697   // Stable recording of a hazard ptr for SMR. This code does not use
       
  3698   // locks so its use of the _smr_java_thread_list & _threads_hazard_ptr
       
  3699   // fields is racy relative to code that uses those fields with locks.
       
  3700   // OrderAccess and Atomic functions are used to deal with those races.
       
  3701   //
       
  3702   while (true) {
       
  3703     threads = get_smr_java_thread_list();
       
  3704 
       
  3705     // Publish a tagged hazard ptr to denote that the hazard ptr is not
       
  3706     // yet verified as being stable. Due to the fence after the hazard
       
  3707     // ptr write, it will be sequentially consistent w.r.t. the
       
  3708     // sequentially consistent writes of the ThreadsList, even on
       
  3709     // non-multiple copy atomic machines where stores can be observed
       
  3710     // in different order from different observer threads.
       
  3711     ThreadsList* unverified_threads = Thread::tag_hazard_ptr(threads);
       
  3712     self->set_threads_hazard_ptr(unverified_threads);
       
  3713 
       
  3714     // If _smr_java_thread_list has changed, we have lost a race with
       
  3715     // Threads::add() or Threads::remove() and have to try again.
       
  3716     if (get_smr_java_thread_list() != threads) {
       
  3717       continue;
       
  3718     }
       
  3719 
       
  3720     // We try to remove the tag which will verify the hazard ptr as
       
  3721     // being stable. This exchange can race with a scanning thread
       
  3722     // which might invalidate the tagged hazard ptr to keep it from
       
  3723     // being followed to access JavaThread ptrs. If we lose the race,
       
  3724     // we simply retry. If we win the race, then the stable hazard
       
  3725     // ptr is officially published.
       
  3726     if (self->cmpxchg_threads_hazard_ptr(threads, unverified_threads) == unverified_threads) {
       
  3727       break;
       
  3728     }
       
  3729   }
       
  3730 
       
  3731   // A stable hazard ptr has been published letting other threads know
       
  3732   // that the ThreadsList and the JavaThreads reachable from this list
       
  3733   // are protected and hence they should not be deleted until everyone
       
  3734   // agrees it is safe to do so.
       
  3735 
       
  3736   return threads;
       
  3737 }
       
  3738 
       
  3739 // Acquire a nested stable ThreadsList; this is rare so it uses
       
  3740 // Threads_lock.
       
  3741 //
       
  3742 ThreadsList *Threads::acquire_stable_list_nested_path(Thread *self) {
       
  3743   assert(self != NULL, "sanity check");
       
  3744   assert(self->get_threads_hazard_ptr() != NULL,
       
  3745          "cannot have a NULL regular hazard ptr when acquiring a nested hazard ptr");
       
  3746 
       
  3747   // The thread already has a hazard ptr (ThreadsList ref) so we need
       
  3748   // to create a nested ThreadsListHandle with the current ThreadsList
       
  3749   // since it might be different than our current hazard ptr. The need
       
  3750   // for a nested ThreadsListHandle is rare so we do this while holding
       
  3751   // the Threads_lock so we don't race with the scanning code; the code
       
  3752   // is so much simpler this way.
       
  3753 
       
  3754   NestedThreadsList* node;
       
  3755   {
       
  3756     // Only grab the Threads_lock if we don't already own it.
       
  3757     MutexLockerEx ml(Threads_lock->owned_by_self() ? NULL : Threads_lock);
       
  3758     node = new NestedThreadsList(get_smr_java_thread_list());
       
  3759     // We insert at the front of the list to match up with the delete
       
  3760     // in release_stable_list().
       
  3761     node->set_next(self->get_nested_threads_hazard_ptr());
       
  3762     self->set_nested_threads_hazard_ptr(node);
       
  3763     if (EnableThreadSMRStatistics) {
       
  3764       self->inc_nested_threads_hazard_ptr_cnt();
       
  3765       if (self->nested_threads_hazard_ptr_cnt() > _smr_nested_thread_list_max) {
       
  3766         _smr_nested_thread_list_max = self->nested_threads_hazard_ptr_cnt();
       
  3767       }
       
  3768     }
       
  3769   }
       
  3770   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::acquire_stable_list: add NestedThreadsList node containing ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(node->t_list()));
       
  3771 
       
  3772   return node->t_list();
       
  3773 }
       
  3774 
       
  3775 // Release a stable ThreadsList.
       
  3776 //
       
  3777 void Threads::release_stable_list(Thread *self) {
       
  3778   assert(self != NULL, "sanity check");
       
  3779   // release_stable_list_nested_path() will grab the Threads_lock
       
  3780   // so let's make sure the ThreadsListHandle is in a safe place.
       
  3781   debug_only(if (StrictSafepointChecks) self->check_for_valid_safepoint_state(/* potential_vm_operation */ false);)
       
  3782 
       
  3783   if (self->get_nested_threads_hazard_ptr() == NULL) {
       
  3784     // The typical case is first.
       
  3785     release_stable_list_fast_path(self);
       
  3786     return;
       
  3787   }
       
  3788 
       
  3789   // The nested case is rare.
       
  3790   release_stable_list_nested_path(self);
       
  3791 }
       
  3792 
       
  3793 // Fast path way to release a stable ThreadsList. The release portion
       
  3794 // is lock-free, but the wake up portion is not.
       
  3795 //
       
  3796 void Threads::release_stable_list_fast_path(Thread *self) {
       
  3797   assert(self != NULL, "sanity check");
       
  3798   assert(self->get_threads_hazard_ptr() != NULL, "sanity check");
       
  3799   assert(self->get_nested_threads_hazard_ptr() == NULL,
       
  3800          "cannot have a nested hazard ptr when releasing a regular hazard ptr");
       
  3801 
       
  3802   // After releasing the hazard ptr, other threads may go ahead and
       
  3803   // free up some memory temporarily used by a ThreadsList snapshot.
       
  3804   self->set_threads_hazard_ptr(NULL);
       
  3805 
       
  3806   // We use double-check locking to reduce traffic on the system
       
  3807   // wide smr_delete_lock.
       
  3808   if (Threads::smr_delete_notify()) {
       
  3809     // An exiting thread might be waiting in smr_delete(); we need to
       
  3810     // check with smr_delete_lock to be sure.
       
  3811     release_stable_list_wake_up((char *) "regular hazard ptr");
       
  3812   }
       
  3813 }
       
  3814 
       
  3815 // Release a nested stable ThreadsList; this is rare so it uses
       
  3816 // Threads_lock.
       
  3817 //
       
  3818 void Threads::release_stable_list_nested_path(Thread *self) {
       
  3819   assert(self != NULL, "sanity check");
       
  3820   assert(self->get_nested_threads_hazard_ptr() != NULL, "sanity check");
       
  3821   assert(self->get_threads_hazard_ptr() != NULL,
       
  3822          "must have a regular hazard ptr to have nested hazard ptrs");
       
  3823 
       
  3824   // We have a nested ThreadsListHandle so we have to release it first.
       
  3825   // The need for a nested ThreadsListHandle is rare so we do this while
       
  3826   // holding the Threads_lock so we don't race with the scanning code;
       
  3827   // the code is so much simpler this way.
       
  3828 
       
  3829   NestedThreadsList *node;
       
  3830   {
       
  3831     // Only grab the Threads_lock if we don't already own it.
       
  3832     MutexLockerEx ml(Threads_lock->owned_by_self() ? NULL : Threads_lock);
       
  3833     // We remove from the front of the list to match up with the insert
       
  3834     // in acquire_stable_list().
       
  3835     node = self->get_nested_threads_hazard_ptr();
       
  3836     self->set_nested_threads_hazard_ptr(node->next());
       
  3837     if (EnableThreadSMRStatistics) {
       
  3838       self->dec_nested_threads_hazard_ptr_cnt();
       
  3839     }
       
  3840   }
       
  3841 
       
  3842   // An exiting thread might be waiting in smr_delete(); we need to
       
  3843   // check with smr_delete_lock to be sure.
       
  3844   release_stable_list_wake_up((char *) "nested hazard ptr");
       
  3845 
       
  3846   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::release_stable_list: delete NestedThreadsList node containing ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(node->t_list()));
       
  3847 
       
  3848   delete node;
       
  3849 }
       
  3850 
       
  3851 // Wake up portion of the release stable ThreadsList protocol;
       
  3852 // uses the smr_delete_lock().
       
  3853 //
       
  3854 void Threads::release_stable_list_wake_up(char *log_str) {
       
  3855   assert(log_str != NULL, "sanity check");
       
  3856 
       
  3857   // Note: smr_delete_lock is held in smr_delete() for the entire
       
  3858   // hazard ptr search so that we do not lose this notify() if
       
  3859   // the exiting thread has to wait. That code path also holds
       
  3860   // Threads_lock (which was grabbed before smr_delete_lock) so that
       
  3861   // threads_do() can be called. This means the system can't start a
       
  3862   // safepoint which means this thread can't take too long to get to
       
  3863   // a safepoint because of being blocked on smr_delete_lock.
       
  3864   //
       
  3865   MonitorLockerEx ml(Threads::smr_delete_lock(), Monitor::_no_safepoint_check_flag);
       
  3866   if (Threads::smr_delete_notify()) {
       
  3867     // Notify any exiting JavaThreads that are waiting in smr_delete()
       
  3868     // that we've released a ThreadsList.
       
  3869     ml.notify_all();
       
  3870     log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::release_stable_list notified %s", os::current_thread_id(), log_str);
       
  3871   }
       
  3872 }
       
  3873 
  3438 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
  3874 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
  3439   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
  3875   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
  3440 
  3876 
  3441   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
  3877   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
  3442     create_vm_init_libraries();
  3878     create_vm_init_libraries();
  3614   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
  4050   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
  3615 
  4051 
  3616   if (!main_thread->set_as_starting_thread()) {
  4052   if (!main_thread->set_as_starting_thread()) {
  3617     vm_shutdown_during_initialization(
  4053     vm_shutdown_during_initialization(
  3618                                       "Failed necessary internal allocation. Out of swap space");
  4054                                       "Failed necessary internal allocation. Out of swap space");
  3619     delete main_thread;
  4055     main_thread->smr_delete();
  3620     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  4056     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  3621     return JNI_ENOMEM;
  4057     return JNI_ENOMEM;
  3622   }
  4058   }
  3623 
  4059 
  3624   // Enable guard page *after* os::create_main_thread(), otherwise it would
  4060   // Enable guard page *after* os::create_main_thread(), otherwise it would
  3629   ObjectMonitor::Initialize();
  4065   ObjectMonitor::Initialize();
  3630 
  4066 
  3631   // Initialize global modules
  4067   // Initialize global modules
  3632   jint status = init_globals();
  4068   jint status = init_globals();
  3633   if (status != JNI_OK) {
  4069   if (status != JNI_OK) {
  3634     delete main_thread;
  4070     main_thread->smr_delete();
  3635     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  4071     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  3636     return status;
  4072     return status;
  3637   }
  4073   }
  3638 
  4074 
  3639   if (TRACE_INITIALIZE() != JNI_OK) {
  4075   if (TRACE_INITIALIZE() != JNI_OK) {
  4035       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
  4471       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
  4036     }
  4472     }
  4037   }
  4473   }
  4038 }
  4474 }
  4039 
  4475 
  4040 JavaThread* Threads::find_java_thread_from_java_tid(jlong java_tid) {
       
  4041   assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
       
  4042 
       
  4043   JavaThread* java_thread = NULL;
       
  4044   // Sequential search for now.  Need to do better optimization later.
       
  4045   for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
       
  4046     oop tobj = thread->threadObj();
       
  4047     if (!thread->is_exiting() &&
       
  4048         tobj != NULL &&
       
  4049         java_tid == java_lang_Thread::thread_id(tobj)) {
       
  4050       java_thread = thread;
       
  4051       break;
       
  4052     }
       
  4053   }
       
  4054   return java_thread;
       
  4055 }
       
  4056 
       
  4057 
  4476 
  4058 // Last thread running calls java.lang.Shutdown.shutdown()
  4477 // Last thread running calls java.lang.Shutdown.shutdown()
  4059 void JavaThread::invoke_shutdown_hooks() {
  4478 void JavaThread::invoke_shutdown_hooks() {
  4060   HandleMark hm(this);
  4479   HandleMark hm(this);
  4061 
  4480 
  4177 
  4596 
  4178   VM_Exit::set_vm_exited();
  4597   VM_Exit::set_vm_exited();
  4179 
  4598 
  4180   notify_vm_shutdown();
  4599   notify_vm_shutdown();
  4181 
  4600 
       
  4601   // We are after VM_Exit::set_vm_exited() so we can't call
       
  4602   // thread->smr_delete() or we will block on the Threads_lock.
       
  4603   // Deleting the shutdown thread here is safe because another
       
  4604   // JavaThread cannot have an active ThreadsListHandle for
       
  4605   // this JavaThread.
  4182   delete thread;
  4606   delete thread;
  4183 
  4607 
  4184 #if INCLUDE_JVMCI
  4608 #if INCLUDE_JVMCI
  4185   if (JVMCICounterSize > 0) {
  4609   if (JVMCICounterSize > 0) {
  4186     FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
  4610     FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
  4210   if (version == JNI_VERSION_9) return JNI_TRUE;
  4634   if (version == JNI_VERSION_9) return JNI_TRUE;
  4211   if (version == JNI_VERSION_10) return JNI_TRUE;
  4635   if (version == JNI_VERSION_10) return JNI_TRUE;
  4212   return JNI_FALSE;
  4636   return JNI_FALSE;
  4213 }
  4637 }
  4214 
  4638 
       
  4639 // Hash table of pointers found by a scan. Used for collecting hazard
       
  4640 // pointers (ThreadsList references). Also used for collecting JavaThreads
       
  4641 // that are indirectly referenced by hazard ptrs. An instance of this
       
  4642 // class only contains one type of pointer.
       
  4643 //
       
  4644 class ThreadScanHashtable : public CHeapObj<mtThread> {
       
  4645  private:
       
  4646   static bool ptr_equals(void * const& s1, void * const& s2) {
       
  4647     return s1 == s2;
       
  4648   }
       
  4649 
       
  4650   static unsigned int ptr_hash(void * const& s1) {
       
  4651     // 2654435761 = 2^32 * Phi (golden ratio)
       
  4652     return (unsigned int)(((uint32_t)(uintptr_t)s1) * 2654435761u);
       
  4653   }
       
  4654 
       
  4655   int _table_size;
       
  4656   // ResourceHashtable SIZE is specified at compile time so our
       
  4657   // dynamic _table_size is unused for now; 1031 is the first prime
       
  4658   // after 1024.
       
  4659   typedef ResourceHashtable<void *, int, &ThreadScanHashtable::ptr_hash,
       
  4660                             &ThreadScanHashtable::ptr_equals, 1031,
       
  4661                             ResourceObj::C_HEAP, mtThread> PtrTable;
       
  4662   PtrTable * _ptrs;
       
  4663 
       
  4664  public:
       
  4665   // ResourceHashtable is passed to various functions and populated in
       
  4666   // different places so we allocate it using C_HEAP to make it immune
       
  4667   // from any ResourceMarks that happen to be in the code paths.
       
  4668   ThreadScanHashtable(int table_size) : _table_size(table_size), _ptrs(new (ResourceObj::C_HEAP, mtThread) PtrTable()) {}
       
  4669 
       
  4670   ~ThreadScanHashtable() { delete _ptrs; }
       
  4671 
       
  4672   bool has_entry(void *pointer) {
       
  4673     int *val_ptr = _ptrs->get(pointer);
       
  4674     return val_ptr != NULL && *val_ptr == 1;
       
  4675   }
       
  4676 
       
  4677   void add_entry(void *pointer) {
       
  4678     _ptrs->put(pointer, 1);
       
  4679   }
       
  4680 };
       
  4681 
       
  4682 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
       
  4683 // (ThreadsList references) into a hash table. This closure handles part 2
       
  4684 // of the dance - adding all the JavaThreads referenced by the hazard
       
  4685 // pointer (ThreadsList reference) to the hash table.
       
  4686 //
       
  4687 class AddThreadHazardPointerThreadClosure : public ThreadClosure {
       
  4688  private:
       
  4689   ThreadScanHashtable *_table;
       
  4690 
       
  4691  public:
       
  4692   AddThreadHazardPointerThreadClosure(ThreadScanHashtable *table) : _table(table) {}
       
  4693 
       
  4694   virtual void do_thread(Thread *thread) {
       
  4695     if (!_table->has_entry((void*)thread)) {
       
  4696       // The same JavaThread might be on more than one ThreadsList or
       
  4697       // more than one thread might be using the same ThreadsList. In
       
  4698       // either case, we only need a single entry for a JavaThread.
       
  4699       _table->add_entry((void*)thread);
       
  4700     }
       
  4701   }
       
  4702 };
       
  4703 
       
  4704 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
       
  4705 // (ThreadsList references) into a hash table. This closure handles part 1
       
  4706 // of the dance - hazard ptr chain walking and dispatch to another
       
  4707 // closure.
       
  4708 //
       
  4709 class ScanHazardPtrGatherProtectedThreadsClosure : public ThreadClosure {
       
  4710  private:
       
  4711   ThreadScanHashtable *_table;
       
  4712  public:
       
  4713   ScanHazardPtrGatherProtectedThreadsClosure(ThreadScanHashtable *table) : _table(table) {}
       
  4714 
       
  4715   virtual void do_thread(Thread *thread) {
       
  4716     assert_locked_or_safepoint(Threads_lock);
       
  4717 
       
  4718     if (thread == NULL) return;
       
  4719 
       
  4720     // This code races with Threads::acquire_stable_list() which is
       
  4721     // lock-free so we have to handle some special situations.
       
  4722     //
       
  4723     ThreadsList *current_list = NULL;
       
  4724     while (true) {
       
  4725       current_list = thread->get_threads_hazard_ptr();
       
  4726       // No hazard ptr so nothing more to do.
       
  4727       if (current_list == NULL) {
       
  4728         assert(thread->get_nested_threads_hazard_ptr() == NULL,
       
  4729                "cannot have a nested hazard ptr with a NULL regular hazard ptr");
       
  4730         return;
       
  4731       }
       
  4732 
       
  4733       // If the hazard ptr is verified as stable (since it is not tagged),
       
  4734       // then it is safe to use.
       
  4735       if (!Thread::is_hazard_ptr_tagged(current_list)) break;
       
  4736 
       
  4737       // The hazard ptr is tagged as not yet verified as being stable
       
  4738       // so we are racing with acquire_stable_list(). This exchange
       
  4739       // attempts to invalidate the hazard ptr. If we win the race,
       
  4740       // then we can ignore this unstable hazard ptr and the other
       
  4741       // thread will retry the attempt to publish a stable hazard ptr.
       
  4742       // If we lose the race, then we retry our attempt to look at the
       
  4743       // hazard ptr.
       
  4744       if (thread->cmpxchg_threads_hazard_ptr(NULL, current_list) == current_list) return;
       
  4745     }
       
  4746 
       
  4747     // The current JavaThread has a hazard ptr (ThreadsList reference)
       
  4748     // which might be _smr_java_thread_list or it might be an older
       
  4749     // ThreadsList that has been removed but not freed. In either case,
       
  4750     // the hazard ptr is protecting all the JavaThreads on that
       
  4751     // ThreadsList.
       
  4752     AddThreadHazardPointerThreadClosure add_cl(_table);
       
  4753     current_list->threads_do(&add_cl);
       
  4754 
       
  4755     // Any NestedThreadsLists are also protecting JavaThreads so
       
  4756     // gather those also; the ThreadsLists may be different.
       
  4757     for (NestedThreadsList* node = thread->get_nested_threads_hazard_ptr();
       
  4758          node != NULL; node = node->next()) {
       
  4759       node->t_list()->threads_do(&add_cl);
       
  4760     }
       
  4761   }
       
  4762 };
       
  4763 
       
  4764 // Closure to print JavaThreads that have a hazard ptr (ThreadsList
       
  4765 // reference) that contains an indirect reference to a specific JavaThread.
       
  4766 //
       
  4767 class ScanHazardPtrPrintMatchingThreadsClosure : public ThreadClosure {
       
  4768  private:
       
  4769   JavaThread *_thread;
       
  4770  public:
       
  4771   ScanHazardPtrPrintMatchingThreadsClosure(JavaThread *thread) : _thread(thread) {}
       
  4772 
       
  4773   virtual void do_thread(Thread *thread) {
       
  4774     assert_locked_or_safepoint(Threads_lock);
       
  4775 
       
  4776     if (thread == NULL) return;
       
  4777     ThreadsList *current_list = thread->get_threads_hazard_ptr();
       
  4778     if (current_list == NULL) {
       
  4779       assert(thread->get_nested_threads_hazard_ptr() == NULL,
       
  4780              "cannot have a nested hazard ptr with a NULL regular hazard ptr");
       
  4781       return;
       
  4782     }
       
  4783     // If the hazard ptr is unverified, then ignore it.
       
  4784     if (Thread::is_hazard_ptr_tagged(current_list)) return;
       
  4785 
       
  4786     // The current JavaThread has a hazard ptr (ThreadsList reference)
       
  4787     // which might be _smr_java_thread_list or it might be an older
       
  4788     // ThreadsList that has been removed but not freed. In either case,
       
  4789     // the hazard ptr is protecting all the JavaThreads on that
       
  4790     // ThreadsList, but we only care about matching a specific JavaThread.
       
  4791     DO_JAVA_THREADS(current_list, p) {
       
  4792       if (p == _thread) {
       
  4793         log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread1=" INTPTR_FORMAT " has a hazard pointer for thread2=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread), p2i(_thread));
       
  4794         break;
       
  4795       }
       
  4796     }
       
  4797 
       
  4798     // Any NestedThreadsLists are also protecting JavaThreads so
       
  4799     // check those also; the ThreadsLists may be different.
       
  4800     for (NestedThreadsList* node = thread->get_nested_threads_hazard_ptr();
       
  4801          node != NULL; node = node->next()) {
       
  4802       DO_JAVA_THREADS(node->t_list(), p) {
       
  4803         if (p == _thread) {
       
  4804           log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread1=" INTPTR_FORMAT " has a nested hazard pointer for thread2=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread), p2i(_thread));
       
  4805           return;
       
  4806         }
       
  4807       }
       
  4808     }
       
  4809   }
       
  4810 };
       
  4811 
       
  4812 // Return true if the specified JavaThread is protected by a hazard
       
  4813 // pointer (ThreadsList reference). Otherwise, returns false.
       
  4814 //
       
  4815 bool Threads::is_a_protected_JavaThread(JavaThread *thread) {
       
  4816   assert_locked_or_safepoint(Threads_lock);
       
  4817 
       
  4818   // Hash table size should be first power of two higher than twice
       
  4819   // the length of the Threads list.
       
  4820   int hash_table_size = MIN2(_number_of_threads, 32) << 1;
       
  4821   hash_table_size--;
       
  4822   hash_table_size |= hash_table_size >> 1;
       
  4823   hash_table_size |= hash_table_size >> 2;
       
  4824   hash_table_size |= hash_table_size >> 4;
       
  4825   hash_table_size |= hash_table_size >> 8;
       
  4826   hash_table_size |= hash_table_size >> 16;
       
  4827   hash_table_size++;
       
  4828 
       
  4829   // Gather a hash table of the JavaThreads indirectly referenced by
       
  4830   // hazard ptrs.
       
  4831   ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
       
  4832   ScanHazardPtrGatherProtectedThreadsClosure scan_cl(scan_table);
       
  4833   Threads::threads_do(&scan_cl);
       
  4834 
       
  4835   bool thread_is_protected = false;
       
  4836   if (scan_table->has_entry((void*)thread)) {
       
  4837     thread_is_protected = true;
       
  4838   }
       
  4839   delete scan_table;
       
  4840   return thread_is_protected;
       
  4841 }
       
  4842 
       
  4843 // Safely delete a JavaThread when it is no longer in use by a
       
  4844 // ThreadsListHandle.
       
  4845 //
       
  4846 void Threads::smr_delete(JavaThread *thread) {
       
  4847   assert(!Threads_lock->owned_by_self(), "sanity");
       
  4848 
       
  4849   bool has_logged_once = false;
       
  4850   elapsedTimer timer;
       
  4851   if (EnableThreadSMRStatistics) {
       
  4852     timer.start();
       
  4853   }
       
  4854 
       
  4855   while (true) {
       
  4856     {
       
  4857       // No safepoint check because this JavaThread is not on the
       
  4858       // Threads list.
       
  4859       MutexLockerEx ml(Threads_lock, Mutex::_no_safepoint_check_flag);
       
  4860       // Cannot use a MonitorLockerEx helper here because we have
       
  4861       // to drop the Threads_lock first if we wait.
       
  4862       Threads::smr_delete_lock()->lock_without_safepoint_check();
       
  4863       // Set the smr_delete_notify flag after we grab smr_delete_lock
       
  4864       // and before we scan hazard ptrs because we're doing
       
  4865       // double-check locking in release_stable_list().
       
  4866       Threads::set_smr_delete_notify();
       
  4867 
       
  4868       if (!is_a_protected_JavaThread(thread)) {
       
  4869         // This is the common case.
       
  4870         Threads::clear_smr_delete_notify();
       
  4871         Threads::smr_delete_lock()->unlock();
       
  4872         break;
       
  4873       }
       
  4874       if (!has_logged_once) {
       
  4875         has_logged_once = true;
       
  4876         log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread=" INTPTR_FORMAT " is not deleted.", os::current_thread_id(), p2i(thread));
       
  4877         if (log_is_enabled(Debug, os, thread)) {
       
  4878           ScanHazardPtrPrintMatchingThreadsClosure scan_cl(thread);
       
  4879           Threads::threads_do(&scan_cl);
       
  4880         }
       
  4881       }
       
  4882     } // We have to drop the Threads_lock to wait or delete the thread
       
  4883 
       
  4884     if (EnableThreadSMRStatistics) {
       
  4885       _smr_delete_lock_wait_cnt++;
       
  4886       if (_smr_delete_lock_wait_cnt > _smr_delete_lock_wait_max) {
       
  4887         _smr_delete_lock_wait_max = _smr_delete_lock_wait_cnt;
       
  4888       }
       
  4889     }
       
  4890     // Wait for a release_stable_list() call before we check again. No
       
  4891     // safepoint check, no timeout, and not as suspend equivalent flag
       
  4892     // because this JavaThread is not on the Threads list.
       
  4893     Threads::smr_delete_lock()->wait(Mutex::_no_safepoint_check_flag, 0,
       
  4894                                      !Mutex::_as_suspend_equivalent_flag);
       
  4895     if (EnableThreadSMRStatistics) {
       
  4896       _smr_delete_lock_wait_cnt--;
       
  4897     }
       
  4898 
       
  4899     Threads::clear_smr_delete_notify();
       
  4900     Threads::smr_delete_lock()->unlock();
       
  4901     // Retry the whole scenario.
       
  4902   }
       
  4903 
       
  4904   if (ThreadLocalHandshakes) {
       
  4905     // The thread is about to be deleted so cancel any handshake.
       
  4906     thread->cancel_handshake();
       
  4907   }
       
  4908 
       
  4909   delete thread;
       
  4910   if (EnableThreadSMRStatistics) {
       
  4911     timer.stop();
       
  4912     uint millis = (uint)timer.milliseconds();
       
  4913     Threads::inc_smr_deleted_thread_cnt();
       
  4914     Threads::add_smr_deleted_thread_times(millis);
       
  4915     Threads::update_smr_deleted_thread_time_max(millis);
       
  4916   }
       
  4917 
       
  4918   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_delete: thread=" INTPTR_FORMAT " is deleted.", os::current_thread_id(), p2i(thread));
       
  4919 }
       
  4920 
       
  4921 bool Threads::smr_delete_notify() {
       
  4922   // Use load_acquire() in order to see any updates to _smr_delete_notify
       
  4923   // earlier than when smr_delete_lock is grabbed.
       
  4924   return (OrderAccess::load_acquire(&_smr_delete_notify) != 0);
       
  4925 }
       
  4926 
       
  4927 // set_smr_delete_notify() and clear_smr_delete_notify() are called
       
  4928 // under the protection of the smr_delete_lock, but we also use an
       
  4929 // Atomic operation to ensure the memory update is seen earlier than
       
  4930 // when the smr_delete_lock is dropped.
       
  4931 //
       
  4932 void Threads::set_smr_delete_notify() {
       
  4933   Atomic::inc(&_smr_delete_notify);
       
  4934 }
       
  4935 
       
  4936 void Threads::clear_smr_delete_notify() {
       
  4937   Atomic::dec(&_smr_delete_notify);
       
  4938 }
       
  4939 
       
  4940 // Closure to gather hazard ptrs (ThreadsList references) into a hash table.
       
  4941 //
       
  4942 class ScanHazardPtrGatherThreadsListClosure : public ThreadClosure {
       
  4943  private:
       
  4944   ThreadScanHashtable *_table;
       
  4945  public:
       
  4946   ScanHazardPtrGatherThreadsListClosure(ThreadScanHashtable *table) : _table(table) {}
       
  4947 
       
  4948   virtual void do_thread(Thread* thread) {
       
  4949     assert_locked_or_safepoint(Threads_lock);
       
  4950 
       
  4951     if (thread == NULL) return;
       
  4952     ThreadsList *threads = thread->get_threads_hazard_ptr();
       
  4953     if (threads == NULL) {
       
  4954       assert(thread->get_nested_threads_hazard_ptr() == NULL,
       
  4955              "cannot have a nested hazard ptr with a NULL regular hazard ptr");
       
  4956       return;
       
  4957     }
       
  4958     // In this closure we always ignore the tag that might mark this
       
  4959     // hazard ptr as not yet verified. If we happen to catch an
       
  4960     // unverified hazard ptr that is subsequently discarded (not
       
  4961     // published), then the only side effect is that we might keep a
       
  4962     // to-be-deleted ThreadsList alive a little longer.
       
  4963     threads = Thread::untag_hazard_ptr(threads);
       
  4964     if (!_table->has_entry((void*)threads)) {
       
  4965       _table->add_entry((void*)threads);
       
  4966     }
       
  4967 
       
  4968     // Any NestedThreadsLists are also protecting JavaThreads so
       
  4969     // gather those also; the ThreadsLists may be different.
       
  4970     for (NestedThreadsList* node = thread->get_nested_threads_hazard_ptr();
       
  4971          node != NULL; node = node->next()) {
       
  4972       threads = node->t_list();
       
  4973       if (!_table->has_entry((void*)threads)) {
       
  4974         _table->add_entry((void*)threads);
       
  4975       }
       
  4976     }
       
  4977   }
       
  4978 };
       
  4979 
       
  4980 // Safely free a ThreadsList after a Threads::add() or Threads::remove().
       
  4981 // The specified ThreadsList may not get deleted during this call if it
       
  4982 // is still in-use (referenced by a hazard ptr). Other ThreadsLists
       
  4983 // in the chain may get deleted by this call if they are no longer in-use.
       
  4984 void Threads::smr_free_list(ThreadsList* threads) {
       
  4985   assert_locked_or_safepoint(Threads_lock);
       
  4986 
       
  4987   threads->set_next_list(_smr_to_delete_list);
       
  4988   _smr_to_delete_list = threads;
       
  4989   if (EnableThreadSMRStatistics) {
       
  4990     _smr_to_delete_list_cnt++;
       
  4991     if (_smr_to_delete_list_cnt > _smr_to_delete_list_max) {
       
  4992       _smr_to_delete_list_max = _smr_to_delete_list_cnt;
       
  4993     }
       
  4994   }
       
  4995 
       
  4996   // Hash table size should be first power of two higher than twice the length of the ThreadsList
       
  4997   int hash_table_size = MIN2(_number_of_threads, 32) << 1;
       
  4998   hash_table_size--;
       
  4999   hash_table_size |= hash_table_size >> 1;
       
  5000   hash_table_size |= hash_table_size >> 2;
       
  5001   hash_table_size |= hash_table_size >> 4;
       
  5002   hash_table_size |= hash_table_size >> 8;
       
  5003   hash_table_size |= hash_table_size >> 16;
       
  5004   hash_table_size++;
       
  5005 
       
  5006   // Gather a hash table of the current hazard ptrs:
       
  5007   ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
       
  5008   ScanHazardPtrGatherThreadsListClosure scan_cl(scan_table);
       
  5009   Threads::threads_do(&scan_cl);
       
  5010 
       
  5011   // Walk through the linked list of pending freeable ThreadsLists
       
  5012   // and free the ones that are not referenced from hazard ptrs.
       
  5013   ThreadsList* current = _smr_to_delete_list;
       
  5014   ThreadsList* prev = NULL;
       
  5015   ThreadsList* next = NULL;
       
  5016   bool threads_is_freed = false;
       
  5017   while (current != NULL) {
       
  5018     next = current->next_list();
       
  5019     if (!scan_table->has_entry((void*)current)) {
       
  5020       // This ThreadsList is not referenced by a hazard ptr.
       
  5021       if (prev != NULL) {
       
  5022         prev->set_next_list(next);
       
  5023       }
       
  5024       if (_smr_to_delete_list == current) {
       
  5025         _smr_to_delete_list = next;
       
  5026       }
       
  5027 
       
  5028       log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_free_list: threads=" INTPTR_FORMAT " is freed.", os::current_thread_id(), p2i(current));
       
  5029       if (current == threads) threads_is_freed = true;
       
  5030       delete current;
       
  5031       if (EnableThreadSMRStatistics) {
       
  5032         _smr_java_thread_list_free_cnt++;
       
  5033         _smr_to_delete_list_cnt--;
       
  5034       }
       
  5035     } else {
       
  5036       prev = current;
       
  5037     }
       
  5038     current = next;
       
  5039   }
       
  5040 
       
  5041   if (!threads_is_freed) {
       
  5042     // Only report "is not freed" on the original call to
       
  5043     // smr_free_list() for this ThreadsList.
       
  5044     log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::smr_free_list: threads=" INTPTR_FORMAT " is not freed.", os::current_thread_id(), p2i(threads));
       
  5045   }
       
  5046 
       
  5047   delete scan_table;
       
  5048 }
       
  5049 
       
  5050 // Remove a JavaThread from a ThreadsList. The returned ThreadsList is a
       
  5051 // new copy of the specified ThreadsList with the specified JavaThread
       
  5052 // removed.
       
  5053 ThreadsList *ThreadsList::remove_thread(ThreadsList* list, JavaThread* java_thread) {
       
  5054   assert(list->_length > 0, "sanity");
       
  5055 
       
  5056   uint i = 0;
       
  5057   DO_JAVA_THREADS(list, current) {
       
  5058     if (current == java_thread) {
       
  5059       break;
       
  5060     }
       
  5061     i++;
       
  5062   }
       
  5063   assert(i < list->_length, "did not find JavaThread on the list");
       
  5064   const uint index = i;
       
  5065   const uint new_length = list->_length - 1;
       
  5066   const uint head_length = index;
       
  5067   const uint tail_length = (new_length >= index) ? (new_length - index) : 0;
       
  5068   ThreadsList *const new_list = new ThreadsList(new_length);
       
  5069 
       
  5070   if (head_length > 0) {
       
  5071     Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
       
  5072   }
       
  5073   if (tail_length > 0) {
       
  5074     Copy::disjoint_words((HeapWord*)list->_threads + index + 1, (HeapWord*)new_list->_threads + index, tail_length);
       
  5075   }
       
  5076 
       
  5077   return new_list;
       
  5078 }
       
  5079 
       
  5080 // Add a JavaThread to a ThreadsList. The returned ThreadsList is a
       
  5081 // new copy of the specified ThreadsList with the specified JavaThread
       
  5082 // appended to the end.
       
  5083 ThreadsList *ThreadsList::add_thread(ThreadsList *list, JavaThread *java_thread) {
       
  5084   const uint index = list->_length;
       
  5085   const uint new_length = index + 1;
       
  5086   const uint head_length = index;
       
  5087   ThreadsList *const new_list = new ThreadsList(new_length);
       
  5088 
       
  5089   if (head_length > 0) {
       
  5090     Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
       
  5091   }
       
  5092   *(JavaThread**)(new_list->_threads + index) = java_thread;
       
  5093 
       
  5094   return new_list;
       
  5095 }
       
  5096 
       
  5097 int ThreadsList::find_index_of_JavaThread(JavaThread *target) {
       
  5098   if (target == NULL) {
       
  5099     return -1;
       
  5100   }
       
  5101   for (uint i = 0; i < length(); i++) {
       
  5102     if (target == thread_at(i)) {
       
  5103       return (int)i;
       
  5104     }
       
  5105   }
       
  5106   return -1;
       
  5107 }
       
  5108 
       
  5109 JavaThread* ThreadsList::find_JavaThread_from_java_tid(jlong java_tid) const {
       
  5110   DO_JAVA_THREADS(this, thread) {
       
  5111     oop tobj = thread->threadObj();
       
  5112     // Ignore the thread if it hasn't run yet, has exited
       
  5113     // or is starting to exit.
       
  5114     if (tobj != NULL && !thread->is_exiting() &&
       
  5115         java_tid == java_lang_Thread::thread_id(tobj)) {
       
  5116       // found a match
       
  5117       return thread;
       
  5118     }
       
  5119   }
       
  5120   return NULL;
       
  5121 }
       
  5122 
       
  5123 bool ThreadsList::includes(const JavaThread * const p) const {
       
  5124   if (p == NULL) {
       
  5125     return false;
       
  5126   }
       
  5127   DO_JAVA_THREADS(this, q) {
       
  5128     if (q == p) {
       
  5129       return true;
       
  5130     }
       
  5131   }
       
  5132   return false;
       
  5133 }
  4215 
  5134 
  4216 void Threads::add(JavaThread* p, bool force_daemon) {
  5135 void Threads::add(JavaThread* p, bool force_daemon) {
  4217   // The threads lock must be owned at this point
  5136   // The threads lock must be owned at this point
  4218   assert_locked_or_safepoint(Threads_lock);
  5137   assert_locked_or_safepoint(Threads_lock);
  4219 
  5138 
  4220   // See the comment for this method in thread.hpp for its purpose and
  5139   // See the comment for this method in thread.hpp for its purpose and
  4221   // why it is called here.
  5140   // why it is called here.
  4222   p->initialize_queues();
  5141   p->initialize_queues();
  4223   p->set_next(_thread_list);
  5142   p->set_next(_thread_list);
  4224   _thread_list = p;
  5143   _thread_list = p;
       
  5144 
       
  5145   // Once a JavaThread is added to the Threads list, smr_delete() has
       
  5146   // to be used to delete it. Otherwise we can just delete it directly.
       
  5147   p->set_on_thread_list();
       
  5148 
  4225   _number_of_threads++;
  5149   _number_of_threads++;
  4226   oop threadObj = p->threadObj();
  5150   oop threadObj = p->threadObj();
  4227   bool daemon = true;
  5151   bool daemon = true;
  4228   // Bootstrapping problem: threadObj can be null for initial
  5152   // Bootstrapping problem: threadObj can be null for initial
  4229   // JavaThread (or for threads attached via JNI)
  5153   // JavaThread (or for threads attached via JNI)
  4232     daemon = false;
  5156     daemon = false;
  4233   }
  5157   }
  4234 
  5158 
  4235   ThreadService::add_thread(p, daemon);
  5159   ThreadService::add_thread(p, daemon);
  4236 
  5160 
       
  5161   // Maintain fast thread list
       
  5162   ThreadsList *new_list = ThreadsList::add_thread(get_smr_java_thread_list(), p);
       
  5163   if (EnableThreadSMRStatistics) {
       
  5164     _smr_java_thread_list_alloc_cnt++;
       
  5165     if (new_list->length() > _smr_java_thread_list_max) {
       
  5166       _smr_java_thread_list_max = new_list->length();
       
  5167     }
       
  5168   }
       
  5169   // Initial _smr_java_thread_list will not generate a "Threads::add" mesg.
       
  5170   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::add: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
       
  5171 
       
  5172   ThreadsList *old_list = xchg_smr_java_thread_list(new_list);
       
  5173   smr_free_list(old_list);
       
  5174 
  4237   // Possible GC point.
  5175   // Possible GC point.
  4238   Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
  5176   Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
  4239 }
  5177 }
  4240 
  5178 
  4241 void Threads::remove(JavaThread* p) {
  5179 void Threads::remove(JavaThread* p) {
  4245 
  5183 
  4246   // Extra scope needed for Thread_lock, so we can check
  5184   // Extra scope needed for Thread_lock, so we can check
  4247   // that we do not remove thread without safepoint code notice
  5185   // that we do not remove thread without safepoint code notice
  4248   { MutexLocker ml(Threads_lock);
  5186   { MutexLocker ml(Threads_lock);
  4249 
  5187 
  4250     assert(includes(p), "p must be present");
  5188     assert(get_smr_java_thread_list()->includes(p), "p must be present");
       
  5189 
       
  5190     // Maintain fast thread list
       
  5191     ThreadsList *new_list = ThreadsList::remove_thread(get_smr_java_thread_list(), p);
       
  5192     if (EnableThreadSMRStatistics) {
       
  5193       _smr_java_thread_list_alloc_cnt++;
       
  5194       // This list is smaller so no need to check for a "longest" update.
       
  5195     }
       
  5196 
       
  5197     // Final _smr_java_thread_list will not generate a "Threads::remove" mesg.
       
  5198     log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::remove: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
       
  5199 
       
  5200     ThreadsList *old_list = xchg_smr_java_thread_list(new_list);
       
  5201     smr_free_list(old_list);
  4251 
  5202 
  4252     JavaThread* current = _thread_list;
  5203     JavaThread* current = _thread_list;
  4253     JavaThread* prev    = NULL;
  5204     JavaThread* prev    = NULL;
  4254 
  5205 
  4255     while (current != p) {
  5206     while (current != p) {
  4260     if (prev) {
  5211     if (prev) {
  4261       prev->set_next(current->next());
  5212       prev->set_next(current->next());
  4262     } else {
  5213     } else {
  4263       _thread_list = p->next();
  5214       _thread_list = p->next();
  4264     }
  5215     }
       
  5216 
  4265     _number_of_threads--;
  5217     _number_of_threads--;
  4266     oop threadObj = p->threadObj();
  5218     oop threadObj = p->threadObj();
  4267     bool daemon = true;
  5219     bool daemon = true;
  4268     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
  5220     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
  4269       _number_of_non_daemon_threads--;
  5221       _number_of_non_daemon_threads--;
  4284     p->set_terminated_value();
  5236     p->set_terminated_value();
  4285   } // unlock Threads_lock
  5237   } // unlock Threads_lock
  4286 
  5238 
  4287   // Since Events::log uses a lock, we grab it outside the Threads_lock
  5239   // Since Events::log uses a lock, we grab it outside the Threads_lock
  4288   Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
  5240   Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
  4289 }
       
  4290 
       
  4291 // Threads_lock must be held when this is called (or must be called during a safepoint)
       
  4292 bool Threads::includes(JavaThread* p) {
       
  4293   assert(Threads_lock->is_locked(), "sanity check");
       
  4294   ALL_JAVA_THREADS(q) {
       
  4295     if (q == p) {
       
  4296       return true;
       
  4297     }
       
  4298   }
       
  4299   return false;
       
  4300 }
  5241 }
  4301 
  5242 
  4302 // Operations on the Threads list for GC.  These are not explicitly locked,
  5243 // Operations on the Threads list for GC.  These are not explicitly locked,
  4303 // but the garbage collector must provide a safe context for them to run.
  5244 // but the garbage collector must provide a safe context for them to run.
  4304 // In particular, these things should never be called when the Threads_lock
  5245 // In particular, these things should never be called when the Threads_lock
  4409   }
  5350   }
  4410 }
  5351 }
  4411 
  5352 
  4412 
  5353 
  4413 // Get count Java threads that are waiting to enter the specified monitor.
  5354 // Get count Java threads that are waiting to enter the specified monitor.
  4414 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
  5355 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
  4415                                                          address monitor,
  5356                                                          int count,
  4416                                                          bool doLock) {
  5357                                                          address monitor) {
  4417   assert(doLock || SafepointSynchronize::is_at_safepoint(),
       
  4418          "must grab Threads_lock or be at safepoint");
       
  4419   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
  5358   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
  4420 
  5359 
  4421   int i = 0;
  5360   int i = 0;
  4422   {
  5361   DO_JAVA_THREADS(t_list, p) {
  4423     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  5362     if (!p->can_call_java()) continue;
  4424     ALL_JAVA_THREADS(p) {
  5363 
  4425       if (!p->can_call_java()) continue;
  5364     address pending = (address)p->current_pending_monitor();
  4426 
  5365     if (pending == monitor) {             // found a match
  4427       address pending = (address)p->current_pending_monitor();
  5366       if (i < count) result->append(p);   // save the first count matches
  4428       if (pending == monitor) {             // found a match
  5367       i++;
  4429         if (i < count) result->append(p);   // save the first count matches
  5368     }
  4430         i++;
  5369   }
  4431       }
  5370 
  4432     }
       
  4433   }
       
  4434   return result;
  5371   return result;
  4435 }
  5372 }
  4436 
  5373 
  4437 
  5374 
  4438 JavaThread *Threads::owning_thread_from_monitor_owner(address owner,
  5375 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
  4439                                                       bool doLock) {
  5376                                                       address owner) {
  4440   assert(doLock ||
       
  4441          Threads_lock->owned_by_self() ||
       
  4442          SafepointSynchronize::is_at_safepoint(),
       
  4443          "must grab Threads_lock or be at safepoint");
       
  4444 
       
  4445   // NULL owner means not locked so we can skip the search
  5377   // NULL owner means not locked so we can skip the search
  4446   if (owner == NULL) return NULL;
  5378   if (owner == NULL) return NULL;
  4447 
  5379 
  4448   {
  5380   DO_JAVA_THREADS(t_list, p) {
  4449     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  5381     // first, see if owner is the address of a Java thread
  4450     ALL_JAVA_THREADS(p) {
  5382     if (owner == (address)p) return p;
  4451       // first, see if owner is the address of a Java thread
  5383   }
  4452       if (owner == (address)p) return p;
  5384 
  4453     }
       
  4454   }
       
  4455   // Cannot assert on lack of success here since this function may be
  5385   // Cannot assert on lack of success here since this function may be
  4456   // used by code that is trying to report useful problem information
  5386   // used by code that is trying to report useful problem information
  4457   // like deadlock detection.
  5387   // like deadlock detection.
  4458   if (UseHeavyMonitors) return NULL;
  5388   if (UseHeavyMonitors) return NULL;
  4459 
  5389 
  4460   // If we didn't find a matching Java thread and we didn't force use of
  5390   // If we didn't find a matching Java thread and we didn't force use of
  4461   // heavyweight monitors, then the owner is the stack address of the
  5391   // heavyweight monitors, then the owner is the stack address of the
  4462   // Lock Word in the owning Java thread's stack.
  5392   // Lock Word in the owning Java thread's stack.
  4463   //
  5393   //
  4464   JavaThread* the_owner = NULL;
  5394   JavaThread* the_owner = NULL;
  4465   {
  5395   DO_JAVA_THREADS(t_list, q) {
  4466     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  5396     if (q->is_lock_owned(owner)) {
  4467     ALL_JAVA_THREADS(q) {
  5397       the_owner = q;
  4468       if (q->is_lock_owned(owner)) {
  5398       break;
  4469         the_owner = q;
  5399     }
  4470         break;
  5400   }
  4471       }
  5401 
  4472     }
       
  4473   }
       
  4474   // cannot assert on lack of success here; see above comment
  5402   // cannot assert on lack of success here; see above comment
  4475   return the_owner;
  5403   return the_owner;
  4476 }
  5404 }
  4477 
  5405 
  4478 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
  5406 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
  4492   ConcurrentLocksDump concurrent_locks;
  5420   ConcurrentLocksDump concurrent_locks;
  4493   if (print_concurrent_locks) {
  5421   if (print_concurrent_locks) {
  4494     concurrent_locks.dump_at_safepoint();
  5422     concurrent_locks.dump_at_safepoint();
  4495   }
  5423   }
  4496 #endif // INCLUDE_SERVICES
  5424 #endif // INCLUDE_SERVICES
       
  5425 
       
  5426   print_smr_info_on(st);
       
  5427   st->cr();
  4497 
  5428 
  4498   ALL_JAVA_THREADS(p) {
  5429   ALL_JAVA_THREADS(p) {
  4499     ResourceMark rm;
  5430     ResourceMark rm;
  4500     p->print_on(st);
  5431     p->print_on(st);
  4501     if (print_stacks) {
  5432     if (print_stacks) {
  4519   WatcherThread* wt = WatcherThread::watcher_thread();
  5450   WatcherThread* wt = WatcherThread::watcher_thread();
  4520   if (wt != NULL) {
  5451   if (wt != NULL) {
  4521     wt->print_on(st);
  5452     wt->print_on(st);
  4522     st->cr();
  5453     st->cr();
  4523   }
  5454   }
       
  5455 
  4524   st->flush();
  5456   st->flush();
       
  5457 }
       
  5458 
       
  5459 // Log Threads class SMR info.
       
  5460 void Threads::log_smr_statistics() {
       
  5461   LogTarget(Info, thread, smr) log;
       
  5462   if (log.is_enabled()) {
       
  5463     LogStream out(log);
       
  5464     print_smr_info_on(&out);
       
  5465   }
       
  5466 }
       
  5467 
       
  5468 // Print Threads class SMR info.
       
  5469 void Threads::print_smr_info_on(outputStream* st) {
       
  5470   // Only grab the Threads_lock if we don't already own it
       
  5471   // and if we are not reporting an error.
       
  5472   MutexLockerEx ml((Threads_lock->owned_by_self() || VMError::is_error_reported()) ? NULL : Threads_lock);
       
  5473 
       
  5474   st->print_cr("Threads class SMR info:");
       
  5475   st->print_cr("_smr_java_thread_list=" INTPTR_FORMAT ", length=%u, "
       
  5476                "elements={", p2i(_smr_java_thread_list),
       
  5477                _smr_java_thread_list->length());
       
  5478   print_smr_info_elements_on(st, _smr_java_thread_list);
       
  5479   st->print_cr("}");
       
  5480   if (_smr_to_delete_list != NULL) {
       
  5481     st->print_cr("_smr_to_delete_list=" INTPTR_FORMAT ", length=%u, "
       
  5482                  "elements={", p2i(_smr_to_delete_list),
       
  5483                  _smr_to_delete_list->length());
       
  5484     print_smr_info_elements_on(st, _smr_to_delete_list);
       
  5485     st->print_cr("}");
       
  5486     for (ThreadsList *t_list = _smr_to_delete_list->next_list();
       
  5487          t_list != NULL; t_list = t_list->next_list()) {
       
  5488       st->print("next-> " INTPTR_FORMAT ", length=%u, "
       
  5489                 "elements={", p2i(t_list), t_list->length());
       
  5490       print_smr_info_elements_on(st, t_list);
       
  5491       st->print_cr("}");
       
  5492     }
       
  5493   }
       
  5494   if (!EnableThreadSMRStatistics) {
       
  5495     return;
       
  5496   }
       
  5497   st->print_cr("_smr_java_thread_list_alloc_cnt=" UINT64_FORMAT ","
       
  5498                "_smr_java_thread_list_free_cnt=" UINT64_FORMAT ","
       
  5499                "_smr_java_thread_list_max=%u, "
       
  5500                "_smr_nested_thread_list_max=%u",
       
  5501                _smr_java_thread_list_alloc_cnt,
       
  5502                _smr_java_thread_list_free_cnt,
       
  5503                _smr_java_thread_list_max,
       
  5504                _smr_nested_thread_list_max);
       
  5505   if (_smr_tlh_cnt > 0) {
       
  5506     st->print_cr("_smr_tlh_cnt=%u"
       
  5507                  ", _smr_tlh_times=%u"
       
  5508                  ", avg_smr_tlh_time=%0.2f"
       
  5509                  ", _smr_tlh_time_max=%u",
       
  5510                  _smr_tlh_cnt, _smr_tlh_times,
       
  5511                  ((double) _smr_tlh_times / _smr_tlh_cnt),
       
  5512                  _smr_tlh_time_max);
       
  5513   }
       
  5514   if (_smr_deleted_thread_cnt > 0) {
       
  5515     st->print_cr("_smr_deleted_thread_cnt=%u"
       
  5516                  ", _smr_deleted_thread_times=%u"
       
  5517                  ", avg_smr_deleted_thread_time=%0.2f"
       
  5518                  ", _smr_deleted_thread_time_max=%u",
       
  5519                  _smr_deleted_thread_cnt, _smr_deleted_thread_times,
       
  5520                  ((double) _smr_deleted_thread_times / _smr_deleted_thread_cnt),
       
  5521                  _smr_deleted_thread_time_max);
       
  5522   }
       
  5523   st->print_cr("_smr_delete_lock_wait_cnt=%u, _smr_delete_lock_wait_max=%u",
       
  5524                _smr_delete_lock_wait_cnt, _smr_delete_lock_wait_max);
       
  5525   st->print_cr("_smr_to_delete_list_cnt=%u, _smr_to_delete_list_max=%u",
       
  5526                _smr_to_delete_list_cnt, _smr_to_delete_list_max);
       
  5527 }
       
  5528 
       
  5529 // Print ThreadsList elements (4 per line).
       
  5530 void Threads::print_smr_info_elements_on(outputStream* st,
       
  5531                                          ThreadsList* t_list) {
       
  5532   uint cnt = 0;
       
  5533   JavaThreadIterator jti(t_list);
       
  5534   for (JavaThread *jt = jti.first(); jt != NULL; jt = jti.next()) {
       
  5535     st->print(INTPTR_FORMAT, p2i(jt));
       
  5536     if (cnt < t_list->length() - 1) {
       
  5537       // Separate with comma or comma-space except for the last one.
       
  5538       if (((cnt + 1) % 4) == 0) {
       
  5539         // Four INTPTR_FORMAT fit on an 80 column line so end the
       
  5540         // current line with just a comma.
       
  5541         st->print_cr(",");
       
  5542       } else {
       
  5543         // Not the last one on the current line so use comma-space:
       
  5544         st->print(", ");
       
  5545       }
       
  5546     } else {
       
  5547       // Last one so just end the current line.
       
  5548       st->cr();
       
  5549     }
       
  5550     cnt++;
       
  5551   }
  4525 }
  5552 }
  4526 
  5553 
  4527 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
  5554 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
  4528                              int buflen, bool* found_current) {
  5555                              int buflen, bool* found_current) {
  4529   if (this_thread != NULL) {
  5556   if (this_thread != NULL) {
  4558 // that VM is not at safepoint and/or current thread is inside signal handler.
  5585 // that VM is not at safepoint and/or current thread is inside signal handler.
  4559 // Don't print stack trace, as the stack may not be walkable. Don't allocate
  5586 // Don't print stack trace, as the stack may not be walkable. Don't allocate
  4560 // memory (even in resource area), it might deadlock the error handler.
  5587 // memory (even in resource area), it might deadlock the error handler.
  4561 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
  5588 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
  4562                              int buflen) {
  5589                              int buflen) {
       
  5590   print_smr_info_on(st);
       
  5591   st->cr();
       
  5592 
  4563   bool found_current = false;
  5593   bool found_current = false;
  4564   st->print_cr("Java Threads: ( => current thread )");
  5594   st->print_cr("Java Threads: ( => current thread )");
  4565   ALL_JAVA_THREADS(thread) {
  5595   ALL_JAVA_THREADS(thread) {
  4566     print_on_error(thread, st, current, buf, buflen, &found_current);
  5596     print_on_error(thread, st, current, buf, buflen, &found_current);
  4567   }
  5597   }
  4579     st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
  5609     st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
  4580     current->print_on_error(st, buf, buflen);
  5610     current->print_on_error(st, buf, buflen);
  4581     st->cr();
  5611     st->cr();
  4582   }
  5612   }
  4583   st->cr();
  5613   st->cr();
       
  5614 
  4584   st->print_cr("Threads with active compile tasks:");
  5615   st->print_cr("Threads with active compile tasks:");
  4585   print_threads_compiling(st, buf, buflen);
  5616   print_threads_compiling(st, buf, buflen);
  4586 }
  5617 }
  4587 
  5618 
  4588 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) {
  5619 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) {