< prev index next >

src/hotspot/share/services/threadService.cpp

Print this page
rev 47819 : imported patch 10.07.open.rebase_20171110.dcubed


  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/systemDictionary.hpp"
  27 #include "memory/allocation.hpp"
  28 #include "memory/heapInspection.hpp"
  29 #include "memory/oopFactory.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/instanceKlass.hpp"
  32 #include "oops/objArrayOop.inline.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "runtime/atomic.hpp"
  35 #include "runtime/handles.inline.hpp"
  36 #include "runtime/init.hpp"
  37 #include "runtime/thread.hpp"
  38 #include "runtime/vframe.hpp"
  39 #include "runtime/thread.inline.hpp"


  40 #include "runtime/vmThread.hpp"
  41 #include "runtime/vm_operations.hpp"
  42 #include "services/threadService.hpp"
  43 
  44 // TODO: we need to define a naming convention for perf counters
  45 // to distinguish counters for:
  46 //   - standard JSR174 use
  47 //   - Hotspot extension (public and committed)
  48 //   - Hotspot extension (private/internal and uncommitted)
  49 
  50 // Default is disabled.
  51 bool ThreadService::_thread_monitoring_contention_enabled = false;
  52 bool ThreadService::_thread_cpu_time_enabled = false;
  53 bool ThreadService::_thread_allocated_memory_enabled = false;
  54 
  55 PerfCounter*  ThreadService::_total_threads_count = NULL;
  56 PerfVariable* ThreadService::_live_threads_count = NULL;
  57 PerfVariable* ThreadService::_peak_threads_count = NULL;
  58 PerfVariable* ThreadService::_daemon_threads_count = NULL;
  59 volatile int ThreadService::_exiting_threads_count = 0;


 131 
 132   if (daemon) {
 133     _daemon_threads_count->set_value(_daemon_threads_count->get_value() - 1);
 134     Atomic::dec((jint*) &_exiting_daemon_threads_count);
 135   }
 136 }
 137 
 138 void ThreadService::current_thread_exiting(JavaThread* jt) {
 139   assert(jt == JavaThread::current(), "Called by current thread");
 140   Atomic::inc((jint*) &_exiting_threads_count);
 141 
 142   oop threadObj = jt->threadObj();
 143   if (threadObj != NULL && java_lang_Thread::is_daemon(threadObj)) {
 144     Atomic::inc((jint*) &_exiting_daemon_threads_count);
 145   }
 146 }
 147 
 148 // FIXME: JVMTI should call this function
 149 Handle ThreadService::get_current_contended_monitor(JavaThread* thread) {
 150   assert(thread != NULL, "should be non-NULL");
 151   assert(Threads_lock->owned_by_self(), "must grab Threads_lock or be at safepoint");
 152 
 153   ObjectMonitor *wait_obj = thread->current_waiting_monitor();
 154 
 155   oop obj = NULL;
 156   if (wait_obj != NULL) {
 157     // thread is doing an Object.wait() call
 158     obj = (oop) wait_obj->object();
 159     assert(obj != NULL, "Object.wait() should have an object");
 160   } else {
 161     ObjectMonitor *enter_obj = thread->current_pending_monitor();
 162     if (enter_obj != NULL) {
 163       // thread is trying to enter() or raw_enter() an ObjectMonitor.
 164       obj = (oop) enter_obj->object();
 165     }
 166     // If obj == NULL, then ObjectMonitor is raw which doesn't count.
 167   }
 168 
 169   Handle h(Thread::current(), obj);
 170   return h;
 171 }


 249 
 250   ThreadDumpResult dump_result;
 251   VM_ThreadDump op(&dump_result,
 252                    threads,
 253                    num_threads,
 254                    -1,    /* entire stack */
 255                    false, /* with locked monitors */
 256                    false  /* with locked synchronizers */);
 257   VMThread::execute(&op);
 258 
 259   // Allocate the resulting StackTraceElement[][] object
 260 
 261   ResourceMark rm(THREAD);
 262   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackTraceElement_array(), true, CHECK_NH);
 263   ObjArrayKlass* ik = ObjArrayKlass::cast(k);
 264   objArrayOop r = oopFactory::new_objArray(ik, num_threads, CHECK_NH);
 265   objArrayHandle result_obj(THREAD, r);
 266 
 267   int num_snapshots = dump_result.num_snapshots();
 268   assert(num_snapshots == num_threads, "Must have num_threads thread snapshots");

 269   int i = 0;
 270   for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; i++, ts = ts->next()) {
 271     ThreadStackTrace* stacktrace = ts->get_stack_trace();
 272     if (stacktrace == NULL) {
 273       // No stack trace
 274       result_obj->obj_at_put(i, NULL);
 275     } else {
 276       // Construct an array of java/lang/StackTraceElement object
 277       Handle backtrace_h = stacktrace->allocate_fill_stack_trace_element_array(CHECK_NH);
 278       result_obj->obj_at_put(i, backtrace_h());
 279     }
 280   }
 281 
 282   return result_obj;
 283 }
 284 
 285 void ThreadService::reset_contention_count_stat(JavaThread* thread) {
 286   ThreadStatistics* stat = thread->get_thread_stat();
 287   if (stat != NULL) {
 288     stat->reset_count_stat();
 289   }
 290 }
 291 
 292 void ThreadService::reset_contention_time_stat(JavaThread* thread) {
 293   ThreadStatistics* stat = thread->get_thread_stat();
 294   if (stat != NULL) {
 295     stat->reset_time_stat();
 296   }
 297 }
 298 
 299 // Find deadlocks involving object monitors and concurrent locks if concurrent_locks is true
 300 DeadlockCycle* ThreadService::find_deadlocks_at_safepoint(bool concurrent_locks) {


 301   // This code was modified from the original Threads::find_deadlocks code.
 302   int globalDfn = 0, thisDfn;
 303   ObjectMonitor* waitingToLockMonitor = NULL;
 304   oop waitingToLockBlocker = NULL;
 305   bool blocked_on_monitor = false;
 306   JavaThread *currentThread, *previousThread;
 307   int num_deadlocks = 0;
 308 
 309   for (JavaThread* p = Threads::first(); p != NULL; p = p->next()) {
 310     // Initialize the depth-first-number
 311     p->set_depth_first_number(-1);

 312   }
 313 
 314   DeadlockCycle* deadlocks = NULL;
 315   DeadlockCycle* last = NULL;
 316   DeadlockCycle* cycle = new DeadlockCycle();
 317   for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
 318     if (jt->depth_first_number() >= 0) {
 319       // this thread was already visited
 320       continue;
 321     }
 322 
 323     thisDfn = globalDfn;
 324     jt->set_depth_first_number(globalDfn++);
 325     previousThread = jt;
 326     currentThread = jt;
 327 
 328     cycle->reset();
 329 
 330     // When there is a deadlock, all the monitors involved in the dependency
 331     // cycle must be contended and heavyweight. So we only care about the
 332     // heavyweight monitor a thread is waiting to lock.
 333     waitingToLockMonitor = (ObjectMonitor*)jt->current_pending_monitor();
 334     if (concurrent_locks) {
 335       waitingToLockBlocker = jt->current_park_blocker();
 336     }
 337     while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) {
 338       cycle->add_thread(currentThread);
 339       if (waitingToLockMonitor != NULL) {
 340         address currentOwner = (address)waitingToLockMonitor->owner();
 341         if (currentOwner != NULL) {
 342           currentThread = Threads::owning_thread_from_monitor_owner(
 343                             currentOwner,
 344                             false /* no locking needed */);
 345           if (currentThread == NULL) {
 346             // This function is called at a safepoint so the JavaThread
 347             // that owns waitingToLockMonitor should be findable, but
 348             // if it is not findable, then the previous currentThread is
 349             // blocked permanently. We record this as a deadlock.
 350             num_deadlocks++;
 351 
 352             cycle->set_deadlock(true);
 353 
 354             // add this cycle to the deadlocks list
 355             if (deadlocks == NULL) {
 356               deadlocks = cycle;
 357             } else {
 358               last->set_next(cycle);
 359             }
 360             last = cycle;
 361             cycle = new DeadlockCycle();
 362             break;
 363           }
 364         }
 365       } else {
 366         if (concurrent_locks) {
 367           if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
 368             oop threadObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);


 369             currentThread = threadObj != NULL ? java_lang_Thread::thread(threadObj) : NULL;
 370           } else {
 371             currentThread = NULL;
 372           }
 373         }
 374       }
 375 
 376       if (currentThread == NULL) {
 377         // No dependency on another thread
 378         break;
 379       }
 380       if (currentThread->depth_first_number() < 0) {
 381         // First visit to this thread
 382         currentThread->set_depth_first_number(globalDfn++);
 383       } else if (currentThread->depth_first_number() < thisDfn) {
 384         // Thread already visited, and not on a (new) cycle
 385         break;
 386       } else if (currentThread == previousThread) {
 387         // Self-loop, ignore
 388         break;


 397           deadlocks = cycle;
 398         } else {
 399           last->set_next(cycle);
 400         }
 401         last = cycle;
 402         cycle = new DeadlockCycle();
 403         break;
 404       }
 405       previousThread = currentThread;
 406       waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
 407       if (concurrent_locks) {
 408         waitingToLockBlocker = currentThread->current_park_blocker();
 409       }
 410     }
 411 
 412   }
 413   delete cycle;
 414   return deadlocks;
 415 }
 416 
 417 ThreadDumpResult::ThreadDumpResult() : _num_threads(0), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
 418 
 419   // Create a new ThreadDumpResult object and append to the list.
 420   // If GC happens before this function returns, Method*
 421   // in the stack trace will be visited.
 422   ThreadService::add_thread_dump(this);
 423 }
 424 
 425 ThreadDumpResult::ThreadDumpResult(int num_threads) : _num_threads(num_threads), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
 426   // Create a new ThreadDumpResult object and append to the list.
 427   // If GC happens before this function returns, oops
 428   // will be visited.
 429   ThreadService::add_thread_dump(this);
 430 }
 431 
 432 ThreadDumpResult::~ThreadDumpResult() {
 433   ThreadService::remove_thread_dump(this);
 434 
 435   // free all the ThreadSnapshot objects created during
 436   // the VM_ThreadDump operation
 437   ThreadSnapshot* ts = _snapshots;
 438   while (ts != NULL) {
 439     ThreadSnapshot* p = ts;
 440     ts = ts->next();
 441     delete p;
 442   }
 443 }
 444 
 445 


 450   if (_snapshots == NULL) {
 451     _snapshots = ts;
 452   } else {
 453     _last->set_next(ts);
 454   }
 455   _last = ts;
 456 }
 457 
 458 void ThreadDumpResult::oops_do(OopClosure* f) {
 459   for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
 460     ts->oops_do(f);
 461   }
 462 }
 463 
 464 void ThreadDumpResult::metadata_do(void f(Metadata*)) {
 465   for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
 466     ts->metadata_do(f);
 467   }
 468 }
 469 




 470 StackFrameInfo::StackFrameInfo(javaVFrame* jvf, bool with_lock_info) {
 471   _method = jvf->method();
 472   _bci = jvf->bci();
 473   _class_holder = _method->method_holder()->klass_holder();
 474   _locked_monitors = NULL;
 475   if (with_lock_info) {
 476     ResourceMark rm;
 477     GrowableArray<MonitorInfo*>* list = jvf->locked_monitors();
 478     int length = list->length();
 479     if (length > 0) {
 480       _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true);
 481       for (int i = 0; i < length; i++) {
 482         MonitorInfo* monitor = list->at(i);
 483         assert(monitor->owner(), "This monitor must have an owning object");
 484         _locked_monitors->append(monitor->owner());
 485       }
 486     }
 487   }
 488 }
 489 


 666 
 667   ResourceMark rm;
 668 
 669   GrowableArray<oop>* aos_objects = new GrowableArray<oop>(INITIAL_ARRAY_SIZE);
 670 
 671   // Find all instances of AbstractOwnableSynchronizer
 672   HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(),
 673                                                 aos_objects);
 674   // Build a map of thread to its owned AQS locks
 675   build_map(aos_objects);
 676 }
 677 
 678 
 679 // build a map of JavaThread to all its owned AbstractOwnableSynchronizer
 680 void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) {
 681   int length = aos_objects->length();
 682   for (int i = 0; i < length; i++) {
 683     oop o = aos_objects->at(i);
 684     oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o);
 685     if (owner_thread_obj != NULL) {


 686       JavaThread* thread = java_lang_Thread::thread(owner_thread_obj);
 687       assert(o->is_instance(), "Must be an instanceOop");
 688       add_lock(thread, (instanceOop) o);
 689     }
 690   }
 691 }
 692 
 693 void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) {
 694   ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread);
 695   if (tcl != NULL) {
 696     tcl->add_lock(o);
 697     return;
 698   }
 699 
 700   // First owned lock found for this thread
 701   tcl = new ThreadConcurrentLocks(thread);
 702   tcl->add_lock(o);
 703   if (_map == NULL) {
 704     _map = tcl;
 705   } else {


 747 void ThreadConcurrentLocks::add_lock(instanceOop o) {
 748   _owned_locks->append(o);
 749 }
 750 
 751 void ThreadConcurrentLocks::oops_do(OopClosure* f) {
 752   int length = _owned_locks->length();
 753   for (int i = 0; i < length; i++) {
 754     f->do_oop((oop*) _owned_locks->adr_at(i));
 755   }
 756 }
 757 
 758 ThreadStatistics::ThreadStatistics() {
 759   _contended_enter_count = 0;
 760   _monitor_wait_count = 0;
 761   _sleep_count = 0;
 762   _count_pending_reset = false;
 763   _timer_pending_reset = false;
 764   memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts));
 765 }
 766 
 767 ThreadSnapshot::ThreadSnapshot(JavaThread* thread) {
 768   _thread = thread;
 769   _threadObj = thread->threadObj();
 770   _stack_trace = NULL;
 771   _concurrent_locks = NULL;
 772   _next = NULL;
 773 
 774   ThreadStatistics* stat = thread->get_thread_stat();
 775   _contended_enter_ticks = stat->contended_enter_ticks();
 776   _contended_enter_count = stat->contended_enter_count();
 777   _monitor_wait_ticks = stat->monitor_wait_ticks();
 778   _monitor_wait_count = stat->monitor_wait_count();
 779   _sleep_ticks = stat->sleep_ticks();
 780   _sleep_count = stat->sleep_count();
 781 
 782   _blocker_object = NULL;
 783   _blocker_object_owner = NULL;
 784 
 785   _thread_status = java_lang_Thread::get_thread_status(_threadObj);
 786   _is_ext_suspended = thread->is_being_ext_suspended();
 787   _is_in_native = (thread->thread_state() == _thread_in_native);
 788 
 789   if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER ||
 790       _thread_status == java_lang_Thread::IN_OBJECT_WAIT ||
 791       _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) {
 792 
 793     Handle obj = ThreadService::get_current_contended_monitor(thread);
 794     if (obj() == NULL) {
 795       // monitor no longer exists; thread is not blocked
 796       _thread_status = java_lang_Thread::RUNNABLE;
 797     } else {
 798       _blocker_object = obj();
 799       JavaThread* owner = ObjectSynchronizer::get_lock_owner(obj, false);
 800       if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER)
 801           || (owner != NULL && owner->is_attaching_via_jni())) {
 802         // ownership information of the monitor is not available
 803         // (may no longer be owned or releasing to some other thread)
 804         // make this thread in RUNNABLE state.
 805         // And when the owner thread is in attaching state, the java thread
 806         // is not completely initialized. For example thread name and id
 807         // and may not be set, so hide the attaching thread.
 808         _thread_status = java_lang_Thread::RUNNABLE;
 809         _blocker_object = NULL;
 810       } else if (owner != NULL) {
 811         _blocker_object_owner = owner->threadObj();
 812       }
 813     }
 814   }
 815 
 816   // Support for JSR-166 locks
 817   if (JDK_Version::current().supports_thread_park_blocker() &&
 818         (_thread_status == java_lang_Thread::PARKED ||
 819          _thread_status == java_lang_Thread::PARKED_TIMED)) {


 848   }
 849 }
 850 
 851 void ThreadSnapshot::metadata_do(void f(Metadata*)) {
 852   if (_stack_trace != NULL) {
 853     _stack_trace->metadata_do(f);
 854   }
 855 }
 856 
 857 
 858 DeadlockCycle::DeadlockCycle() {
 859   _is_deadlock = false;
 860   _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true);
 861   _next = NULL;
 862 }
 863 
 864 DeadlockCycle::~DeadlockCycle() {
 865   delete _threads;
 866 }
 867 
 868 void DeadlockCycle::print_on(outputStream* st) const {
 869   st->cr();
 870   st->print_cr("Found one Java-level deadlock:");
 871   st->print("=============================");
 872 
 873   JavaThread* currentThread;
 874   ObjectMonitor* waitingToLockMonitor;
 875   oop waitingToLockBlocker;
 876   int len = _threads->length();
 877   for (int i = 0; i < len; i++) {
 878     currentThread = _threads->at(i);
 879     waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
 880     waitingToLockBlocker = currentThread->current_park_blocker();
 881     st->cr();
 882     st->print_cr("\"%s\":", currentThread->get_thread_name());
 883     const char* owner_desc = ",\n  which is held by";
 884     if (waitingToLockMonitor != NULL) {
 885       st->print("  waiting to lock monitor " INTPTR_FORMAT, p2i(waitingToLockMonitor));
 886       oop obj = (oop)waitingToLockMonitor->object();
 887       if (obj != NULL) {
 888         st->print(" (object " INTPTR_FORMAT ", a %s)", p2i(obj),
 889                    obj->klass()->external_name());
 890 
 891         if (!currentThread->current_pending_monitor_is_from_java()) {
 892           owner_desc = "\n  in JNI, which is held by";
 893         }
 894       } else {
 895         // No Java object associated - a JVMTI raw monitor
 896         owner_desc = " (JVMTI raw monitor),\n  which is held by";
 897       }
 898       currentThread = Threads::owning_thread_from_monitor_owner(
 899                         (address)waitingToLockMonitor->owner(),
 900                         false /* no locking needed */);
 901       if (currentThread == NULL) {
 902         // The deadlock was detected at a safepoint so the JavaThread
 903         // that owns waitingToLockMonitor should be findable, but
 904         // if it is not findable, then the previous currentThread is
 905         // blocked permanently.
 906         st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc,
 907                   p2i(waitingToLockMonitor->owner()));
 908         continue;
 909       }
 910     } else {
 911       st->print("  waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
 912                 p2i(waitingToLockBlocker),
 913                 waitingToLockBlocker->klass()->external_name());
 914       assert(waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass()),
 915              "Must be an AbstractOwnableSynchronizer");
 916       oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
 917       currentThread = java_lang_Thread::thread(ownerObj);

 918     }
 919     st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name());
 920   }
 921 
 922   st->cr();
 923   st->cr();
 924 
 925   // Print stack traces
 926   bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace;
 927   JavaMonitorsInStackTrace = true;
 928   st->print_cr("Java stack information for the threads listed above:");
 929   st->print_cr("===================================================");
 930   for (int j = 0; j < len; j++) {
 931     currentThread = _threads->at(j);
 932     st->print_cr("\"%s\":", currentThread->get_thread_name());
 933     currentThread->print_stack_on(st);
 934   }
 935   JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace;
 936 }
 937 
 938 ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread,
 939                                              bool include_jvmti_agent_threads,
 940                                              bool include_jni_attaching_threads) {
 941   assert(cur_thread == Thread::current(), "Check current thread");
 942 
 943   int init_size = ThreadService::get_live_thread_count();
 944   _threads_array = new GrowableArray<instanceHandle>(init_size);
 945 
 946   MutexLockerEx ml(Threads_lock);
 947 
 948   for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
 949     // skips JavaThreads in the process of exiting
 950     // and also skips VM internal JavaThreads
 951     // Threads in _thread_new or _thread_new_trans state are included.
 952     // i.e. threads have been started but not yet running.
 953     if (jt->threadObj() == NULL   ||
 954         jt->is_exiting() ||
 955         !java_lang_Thread::is_alive(jt->threadObj())   ||
 956         jt->is_hidden_from_external_view()) {
 957       continue;
 958     }
 959 
 960     // skip agent threads
 961     if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) {
 962       continue;
 963     }
 964 
 965     // skip jni threads in the process of attaching
 966     if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) {
 967       continue;
 968     }


  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/systemDictionary.hpp"
  27 #include "memory/allocation.hpp"
  28 #include "memory/heapInspection.hpp"
  29 #include "memory/oopFactory.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/instanceKlass.hpp"
  32 #include "oops/objArrayOop.inline.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "runtime/atomic.hpp"
  35 #include "runtime/handles.inline.hpp"
  36 #include "runtime/init.hpp"


  37 #include "runtime/thread.inline.hpp"
  38 #include "runtime/threadSMR.inline.hpp"
  39 #include "runtime/vframe.hpp"
  40 #include "runtime/vmThread.hpp"
  41 #include "runtime/vm_operations.hpp"
  42 #include "services/threadService.hpp"
  43 
  44 // TODO: we need to define a naming convention for perf counters
  45 // to distinguish counters for:
  46 //   - standard JSR174 use
  47 //   - Hotspot extension (public and committed)
  48 //   - Hotspot extension (private/internal and uncommitted)
  49 
  50 // Default is disabled.
  51 bool ThreadService::_thread_monitoring_contention_enabled = false;
  52 bool ThreadService::_thread_cpu_time_enabled = false;
  53 bool ThreadService::_thread_allocated_memory_enabled = false;
  54 
  55 PerfCounter*  ThreadService::_total_threads_count = NULL;
  56 PerfVariable* ThreadService::_live_threads_count = NULL;
  57 PerfVariable* ThreadService::_peak_threads_count = NULL;
  58 PerfVariable* ThreadService::_daemon_threads_count = NULL;
  59 volatile int ThreadService::_exiting_threads_count = 0;


 131 
 132   if (daemon) {
 133     _daemon_threads_count->set_value(_daemon_threads_count->get_value() - 1);
 134     Atomic::dec((jint*) &_exiting_daemon_threads_count);
 135   }
 136 }
 137 
 138 void ThreadService::current_thread_exiting(JavaThread* jt) {
 139   assert(jt == JavaThread::current(), "Called by current thread");
 140   Atomic::inc((jint*) &_exiting_threads_count);
 141 
 142   oop threadObj = jt->threadObj();
 143   if (threadObj != NULL && java_lang_Thread::is_daemon(threadObj)) {
 144     Atomic::inc((jint*) &_exiting_daemon_threads_count);
 145   }
 146 }
 147 
 148 // FIXME: JVMTI should call this function
 149 Handle ThreadService::get_current_contended_monitor(JavaThread* thread) {
 150   assert(thread != NULL, "should be non-NULL");
 151   debug_only(Thread::check_for_dangling_thread_pointer(thread);)
 152 
 153   ObjectMonitor *wait_obj = thread->current_waiting_monitor();
 154 
 155   oop obj = NULL;
 156   if (wait_obj != NULL) {
 157     // thread is doing an Object.wait() call
 158     obj = (oop) wait_obj->object();
 159     assert(obj != NULL, "Object.wait() should have an object");
 160   } else {
 161     ObjectMonitor *enter_obj = thread->current_pending_monitor();
 162     if (enter_obj != NULL) {
 163       // thread is trying to enter() or raw_enter() an ObjectMonitor.
 164       obj = (oop) enter_obj->object();
 165     }
 166     // If obj == NULL, then ObjectMonitor is raw which doesn't count.
 167   }
 168 
 169   Handle h(Thread::current(), obj);
 170   return h;
 171 }


 249 
 250   ThreadDumpResult dump_result;
 251   VM_ThreadDump op(&dump_result,
 252                    threads,
 253                    num_threads,
 254                    -1,    /* entire stack */
 255                    false, /* with locked monitors */
 256                    false  /* with locked synchronizers */);
 257   VMThread::execute(&op);
 258 
 259   // Allocate the resulting StackTraceElement[][] object
 260 
 261   ResourceMark rm(THREAD);
 262   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackTraceElement_array(), true, CHECK_NH);
 263   ObjArrayKlass* ik = ObjArrayKlass::cast(k);
 264   objArrayOop r = oopFactory::new_objArray(ik, num_threads, CHECK_NH);
 265   objArrayHandle result_obj(THREAD, r);
 266 
 267   int num_snapshots = dump_result.num_snapshots();
 268   assert(num_snapshots == num_threads, "Must have num_threads thread snapshots");
 269   assert(num_snapshots == 0 || dump_result.t_list_has_been_set(), "ThreadsList must have been set if we have a snapshot");
 270   int i = 0;
 271   for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; i++, ts = ts->next()) {
 272     ThreadStackTrace* stacktrace = ts->get_stack_trace();
 273     if (stacktrace == NULL) {
 274       // No stack trace
 275       result_obj->obj_at_put(i, NULL);
 276     } else {
 277       // Construct an array of java/lang/StackTraceElement object
 278       Handle backtrace_h = stacktrace->allocate_fill_stack_trace_element_array(CHECK_NH);
 279       result_obj->obj_at_put(i, backtrace_h());
 280     }
 281   }
 282 
 283   return result_obj;
 284 }
 285 
 286 void ThreadService::reset_contention_count_stat(JavaThread* thread) {
 287   ThreadStatistics* stat = thread->get_thread_stat();
 288   if (stat != NULL) {
 289     stat->reset_count_stat();
 290   }
 291 }
 292 
 293 void ThreadService::reset_contention_time_stat(JavaThread* thread) {
 294   ThreadStatistics* stat = thread->get_thread_stat();
 295   if (stat != NULL) {
 296     stat->reset_time_stat();
 297   }
 298 }
 299 
 300 // Find deadlocks involving object monitors and concurrent locks if concurrent_locks is true
 301 DeadlockCycle* ThreadService::find_deadlocks_at_safepoint(ThreadsList * t_list, bool concurrent_locks) {
 302   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 303 
 304   // This code was modified from the original Threads::find_deadlocks code.
 305   int globalDfn = 0, thisDfn;
 306   ObjectMonitor* waitingToLockMonitor = NULL;
 307   oop waitingToLockBlocker = NULL;
 308   bool blocked_on_monitor = false;
 309   JavaThread *currentThread, *previousThread;
 310   int num_deadlocks = 0;
 311 
 312   // Initialize the depth-first-number for each JavaThread.
 313   JavaThreadIterator jti(t_list);
 314   for (JavaThread* jt = jti.first(); jt != NULL; jt = jti.next()) {
 315     jt->set_depth_first_number(-1);
 316   }
 317 
 318   DeadlockCycle* deadlocks = NULL;
 319   DeadlockCycle* last = NULL;
 320   DeadlockCycle* cycle = new DeadlockCycle();
 321   for (JavaThread* jt = jti.first(); jt != NULL; jt = jti.next()) {
 322     if (jt->depth_first_number() >= 0) {
 323       // this thread was already visited
 324       continue;
 325     }
 326 
 327     thisDfn = globalDfn;
 328     jt->set_depth_first_number(globalDfn++);
 329     previousThread = jt;
 330     currentThread = jt;
 331 
 332     cycle->reset();
 333 
 334     // When there is a deadlock, all the monitors involved in the dependency
 335     // cycle must be contended and heavyweight. So we only care about the
 336     // heavyweight monitor a thread is waiting to lock.
 337     waitingToLockMonitor = (ObjectMonitor*)jt->current_pending_monitor();
 338     if (concurrent_locks) {
 339       waitingToLockBlocker = jt->current_park_blocker();
 340     }
 341     while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) {
 342       cycle->add_thread(currentThread);
 343       if (waitingToLockMonitor != NULL) {
 344         address currentOwner = (address)waitingToLockMonitor->owner();
 345         if (currentOwner != NULL) {
 346           currentThread = Threads::owning_thread_from_monitor_owner(t_list,
 347                                                                     currentOwner);

 348           if (currentThread == NULL) {
 349             // This function is called at a safepoint so the JavaThread
 350             // that owns waitingToLockMonitor should be findable, but
 351             // if it is not findable, then the previous currentThread is
 352             // blocked permanently. We record this as a deadlock.
 353             num_deadlocks++;
 354 
 355             cycle->set_deadlock(true);
 356 
 357             // add this cycle to the deadlocks list
 358             if (deadlocks == NULL) {
 359               deadlocks = cycle;
 360             } else {
 361               last->set_next(cycle);
 362             }
 363             last = cycle;
 364             cycle = new DeadlockCycle();
 365             break;
 366           }
 367         }
 368       } else {
 369         if (concurrent_locks) {
 370           if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
 371             oop threadObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
 372             // This JavaThread (if there is one) is protected by the
 373             // ThreadsListSetter in VM_FindDeadlocks::doit().
 374             currentThread = threadObj != NULL ? java_lang_Thread::thread(threadObj) : NULL;
 375           } else {
 376             currentThread = NULL;
 377           }
 378         }
 379       }
 380 
 381       if (currentThread == NULL) {
 382         // No dependency on another thread
 383         break;
 384       }
 385       if (currentThread->depth_first_number() < 0) {
 386         // First visit to this thread
 387         currentThread->set_depth_first_number(globalDfn++);
 388       } else if (currentThread->depth_first_number() < thisDfn) {
 389         // Thread already visited, and not on a (new) cycle
 390         break;
 391       } else if (currentThread == previousThread) {
 392         // Self-loop, ignore
 393         break;


 402           deadlocks = cycle;
 403         } else {
 404           last->set_next(cycle);
 405         }
 406         last = cycle;
 407         cycle = new DeadlockCycle();
 408         break;
 409       }
 410       previousThread = currentThread;
 411       waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
 412       if (concurrent_locks) {
 413         waitingToLockBlocker = currentThread->current_park_blocker();
 414       }
 415     }
 416 
 417   }
 418   delete cycle;
 419   return deadlocks;
 420 }
 421 
 422 ThreadDumpResult::ThreadDumpResult() : _num_threads(0), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL), _setter() {
 423 
 424   // Create a new ThreadDumpResult object and append to the list.
 425   // If GC happens before this function returns, Method*
 426   // in the stack trace will be visited.
 427   ThreadService::add_thread_dump(this);
 428 }
 429 
 430 ThreadDumpResult::ThreadDumpResult(int num_threads) : _num_threads(num_threads), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL), _setter() {
 431   // Create a new ThreadDumpResult object and append to the list.
 432   // If GC happens before this function returns, oops
 433   // will be visited.
 434   ThreadService::add_thread_dump(this);
 435 }
 436 
 437 ThreadDumpResult::~ThreadDumpResult() {
 438   ThreadService::remove_thread_dump(this);
 439 
 440   // free all the ThreadSnapshot objects created during
 441   // the VM_ThreadDump operation
 442   ThreadSnapshot* ts = _snapshots;
 443   while (ts != NULL) {
 444     ThreadSnapshot* p = ts;
 445     ts = ts->next();
 446     delete p;
 447   }
 448 }
 449 
 450 


 455   if (_snapshots == NULL) {
 456     _snapshots = ts;
 457   } else {
 458     _last->set_next(ts);
 459   }
 460   _last = ts;
 461 }
 462 
 463 void ThreadDumpResult::oops_do(OopClosure* f) {
 464   for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
 465     ts->oops_do(f);
 466   }
 467 }
 468 
 469 void ThreadDumpResult::metadata_do(void f(Metadata*)) {
 470   for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
 471     ts->metadata_do(f);
 472   }
 473 }
 474 
 475 ThreadsList* ThreadDumpResult::t_list() {
 476   return _setter.list();
 477 }
 478 
 479 StackFrameInfo::StackFrameInfo(javaVFrame* jvf, bool with_lock_info) {
 480   _method = jvf->method();
 481   _bci = jvf->bci();
 482   _class_holder = _method->method_holder()->klass_holder();
 483   _locked_monitors = NULL;
 484   if (with_lock_info) {
 485     ResourceMark rm;
 486     GrowableArray<MonitorInfo*>* list = jvf->locked_monitors();
 487     int length = list->length();
 488     if (length > 0) {
 489       _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true);
 490       for (int i = 0; i < length; i++) {
 491         MonitorInfo* monitor = list->at(i);
 492         assert(monitor->owner(), "This monitor must have an owning object");
 493         _locked_monitors->append(monitor->owner());
 494       }
 495     }
 496   }
 497 }
 498 


 675 
 676   ResourceMark rm;
 677 
 678   GrowableArray<oop>* aos_objects = new GrowableArray<oop>(INITIAL_ARRAY_SIZE);
 679 
 680   // Find all instances of AbstractOwnableSynchronizer
 681   HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(),
 682                                                 aos_objects);
 683   // Build a map of thread to its owned AQS locks
 684   build_map(aos_objects);
 685 }
 686 
 687 
 688 // build a map of JavaThread to all its owned AbstractOwnableSynchronizer
 689 void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) {
 690   int length = aos_objects->length();
 691   for (int i = 0; i < length; i++) {
 692     oop o = aos_objects->at(i);
 693     oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o);
 694     if (owner_thread_obj != NULL) {
 695       // See comments in ThreadConcurrentLocks to see how this
 696       // JavaThread* is protected.
 697       JavaThread* thread = java_lang_Thread::thread(owner_thread_obj);
 698       assert(o->is_instance(), "Must be an instanceOop");
 699       add_lock(thread, (instanceOop) o);
 700     }
 701   }
 702 }
 703 
 704 void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) {
 705   ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread);
 706   if (tcl != NULL) {
 707     tcl->add_lock(o);
 708     return;
 709   }
 710 
 711   // First owned lock found for this thread
 712   tcl = new ThreadConcurrentLocks(thread);
 713   tcl->add_lock(o);
 714   if (_map == NULL) {
 715     _map = tcl;
 716   } else {


 758 void ThreadConcurrentLocks::add_lock(instanceOop o) {
 759   _owned_locks->append(o);
 760 }
 761 
 762 void ThreadConcurrentLocks::oops_do(OopClosure* f) {
 763   int length = _owned_locks->length();
 764   for (int i = 0; i < length; i++) {
 765     f->do_oop((oop*) _owned_locks->adr_at(i));
 766   }
 767 }
 768 
 769 ThreadStatistics::ThreadStatistics() {
 770   _contended_enter_count = 0;
 771   _monitor_wait_count = 0;
 772   _sleep_count = 0;
 773   _count_pending_reset = false;
 774   _timer_pending_reset = false;
 775   memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts));
 776 }
 777 
 778 ThreadSnapshot::ThreadSnapshot(ThreadsList * t_list, JavaThread* thread) {
 779   _thread = thread;
 780   _threadObj = thread->threadObj();
 781   _stack_trace = NULL;
 782   _concurrent_locks = NULL;
 783   _next = NULL;
 784 
 785   ThreadStatistics* stat = thread->get_thread_stat();
 786   _contended_enter_ticks = stat->contended_enter_ticks();
 787   _contended_enter_count = stat->contended_enter_count();
 788   _monitor_wait_ticks = stat->monitor_wait_ticks();
 789   _monitor_wait_count = stat->monitor_wait_count();
 790   _sleep_ticks = stat->sleep_ticks();
 791   _sleep_count = stat->sleep_count();
 792 
 793   _blocker_object = NULL;
 794   _blocker_object_owner = NULL;
 795 
 796   _thread_status = java_lang_Thread::get_thread_status(_threadObj);
 797   _is_ext_suspended = thread->is_being_ext_suspended();
 798   _is_in_native = (thread->thread_state() == _thread_in_native);
 799 
 800   if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER ||
 801       _thread_status == java_lang_Thread::IN_OBJECT_WAIT ||
 802       _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) {
 803 
 804     Handle obj = ThreadService::get_current_contended_monitor(thread);
 805     if (obj() == NULL) {
 806       // monitor no longer exists; thread is not blocked
 807       _thread_status = java_lang_Thread::RUNNABLE;
 808     } else {
 809       _blocker_object = obj();
 810       JavaThread* owner = ObjectSynchronizer::get_lock_owner(t_list, obj);
 811       if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER)
 812           || (owner != NULL && owner->is_attaching_via_jni())) {
 813         // ownership information of the monitor is not available
 814         // (may no longer be owned or releasing to some other thread)
 815         // make this thread in RUNNABLE state.
 816         // And when the owner thread is in attaching state, the java thread
 817         // is not completely initialized. For example thread name and id
 818         // and may not be set, so hide the attaching thread.
 819         _thread_status = java_lang_Thread::RUNNABLE;
 820         _blocker_object = NULL;
 821       } else if (owner != NULL) {
 822         _blocker_object_owner = owner->threadObj();
 823       }
 824     }
 825   }
 826 
 827   // Support for JSR-166 locks
 828   if (JDK_Version::current().supports_thread_park_blocker() &&
 829         (_thread_status == java_lang_Thread::PARKED ||
 830          _thread_status == java_lang_Thread::PARKED_TIMED)) {


 859   }
 860 }
 861 
 862 void ThreadSnapshot::metadata_do(void f(Metadata*)) {
 863   if (_stack_trace != NULL) {
 864     _stack_trace->metadata_do(f);
 865   }
 866 }
 867 
 868 
 869 DeadlockCycle::DeadlockCycle() {
 870   _is_deadlock = false;
 871   _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true);
 872   _next = NULL;
 873 }
 874 
 875 DeadlockCycle::~DeadlockCycle() {
 876   delete _threads;
 877 }
 878 
 879 void DeadlockCycle::print_on_with(ThreadsList * t_list, outputStream* st) const {
 880   st->cr();
 881   st->print_cr("Found one Java-level deadlock:");
 882   st->print("=============================");
 883 
 884   JavaThread* currentThread;
 885   ObjectMonitor* waitingToLockMonitor;
 886   oop waitingToLockBlocker;
 887   int len = _threads->length();
 888   for (int i = 0; i < len; i++) {
 889     currentThread = _threads->at(i);
 890     waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
 891     waitingToLockBlocker = currentThread->current_park_blocker();
 892     st->cr();
 893     st->print_cr("\"%s\":", currentThread->get_thread_name());
 894     const char* owner_desc = ",\n  which is held by";
 895     if (waitingToLockMonitor != NULL) {
 896       st->print("  waiting to lock monitor " INTPTR_FORMAT, p2i(waitingToLockMonitor));
 897       oop obj = (oop)waitingToLockMonitor->object();
 898       if (obj != NULL) {
 899         st->print(" (object " INTPTR_FORMAT ", a %s)", p2i(obj),
 900                    obj->klass()->external_name());
 901 
 902         if (!currentThread->current_pending_monitor_is_from_java()) {
 903           owner_desc = "\n  in JNI, which is held by";
 904         }
 905       } else {
 906         // No Java object associated - a JVMTI raw monitor
 907         owner_desc = " (JVMTI raw monitor),\n  which is held by";
 908       }
 909       currentThread = Threads::owning_thread_from_monitor_owner(t_list,
 910                                                                 (address)waitingToLockMonitor->owner());

 911       if (currentThread == NULL) {
 912         // The deadlock was detected at a safepoint so the JavaThread
 913         // that owns waitingToLockMonitor should be findable, but
 914         // if it is not findable, then the previous currentThread is
 915         // blocked permanently.
 916         st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc,
 917                   p2i(waitingToLockMonitor->owner()));
 918         continue;
 919       }
 920     } else {
 921       st->print("  waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
 922                 p2i(waitingToLockBlocker),
 923                 waitingToLockBlocker->klass()->external_name());
 924       assert(waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass()),
 925              "Must be an AbstractOwnableSynchronizer");
 926       oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
 927       currentThread = java_lang_Thread::thread(ownerObj);
 928       assert(currentThread != NULL, "AbstractOwnableSynchronizer owning thread is unexpectedly NULL");
 929     }
 930     st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name());
 931   }
 932 
 933   st->cr();
 934   st->cr();
 935 
 936   // Print stack traces
 937   bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace;
 938   JavaMonitorsInStackTrace = true;
 939   st->print_cr("Java stack information for the threads listed above:");
 940   st->print_cr("===================================================");
 941   for (int j = 0; j < len; j++) {
 942     currentThread = _threads->at(j);
 943     st->print_cr("\"%s\":", currentThread->get_thread_name());
 944     currentThread->print_stack_on(st);
 945   }
 946   JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace;
 947 }
 948 
 949 ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread,
 950                                              bool include_jvmti_agent_threads,
 951                                              bool include_jni_attaching_threads) {
 952   assert(cur_thread == Thread::current(), "Check current thread");
 953 
 954   int init_size = ThreadService::get_live_thread_count();
 955   _threads_array = new GrowableArray<instanceHandle>(init_size);
 956 
 957   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {


 958     // skips JavaThreads in the process of exiting
 959     // and also skips VM internal JavaThreads
 960     // Threads in _thread_new or _thread_new_trans state are included.
 961     // i.e. threads have been started but not yet running.
 962     if (jt->threadObj() == NULL   ||
 963         jt->is_exiting() ||
 964         !java_lang_Thread::is_alive(jt->threadObj())   ||
 965         jt->is_hidden_from_external_view()) {
 966       continue;
 967     }
 968 
 969     // skip agent threads
 970     if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) {
 971       continue;
 972     }
 973 
 974     // skip jni threads in the process of attaching
 975     if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) {
 976       continue;
 977     }
< prev index next >