1 /* 2 * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 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 "oops/instanceKlass.hpp" 31 #include "oops/oop.inline.hpp" 32 #include "runtime/handles.inline.hpp" 33 #include "runtime/init.hpp" 34 #include "runtime/thread.hpp" 35 #include "runtime/vframe.hpp" 36 #include "runtime/vmThread.hpp" 37 #include "runtime/vm_operations.hpp" 38 #include "services/threadService.hpp" 39 40 // TODO: we need to define a naming convention for perf counters 41 // to distinguish counters for: 42 // - standard JSR174 use 43 // - Hotspot extension (public and committed) 44 // - Hotspot extension (private/internal and uncommitted) 45 46 // Default is disabled. 47 bool ThreadService::_thread_monitoring_contention_enabled = false; 48 bool ThreadService::_thread_cpu_time_enabled = false; 49 bool ThreadService::_thread_allocated_memory_enabled = false; 50 51 PerfCounter* ThreadService::_total_threads_count = NULL; 52 PerfVariable* ThreadService::_live_threads_count = NULL; 53 PerfVariable* ThreadService::_peak_threads_count = NULL; 54 PerfVariable* ThreadService::_daemon_threads_count = NULL; 55 volatile int ThreadService::_exiting_threads_count = 0; 56 volatile int ThreadService::_exiting_daemon_threads_count = 0; 57 58 ThreadDumpResult* ThreadService::_threaddump_list = NULL; 59 60 static const int INITIAL_ARRAY_SIZE = 10; 61 62 void ThreadService::init() { 63 EXCEPTION_MARK; 64 65 // These counters are for java.lang.management API support. 66 // They are created even if -XX:-UsePerfData is set and in 67 // that case, they will be allocated on C heap. 68 69 _total_threads_count = 70 PerfDataManager::create_counter(JAVA_THREADS, "started", 71 PerfData::U_Events, CHECK); 72 73 _live_threads_count = 74 PerfDataManager::create_variable(JAVA_THREADS, "live", 75 PerfData::U_None, CHECK); 76 77 _peak_threads_count = 78 PerfDataManager::create_variable(JAVA_THREADS, "livePeak", 79 PerfData::U_None, CHECK); 80 81 _daemon_threads_count = 82 PerfDataManager::create_variable(JAVA_THREADS, "daemon", 83 PerfData::U_None, CHECK); 84 85 if (os::is_thread_cpu_time_supported()) { 86 _thread_cpu_time_enabled = true; 87 } 88 89 _thread_allocated_memory_enabled = true; // Always on, so enable it 90 } 91 92 void ThreadService::reset_peak_thread_count() { 93 // Acquire the lock to update the peak thread count 94 // to synchronize with thread addition and removal. 95 MutexLockerEx mu(Threads_lock); 96 _peak_threads_count->set_value(get_live_thread_count()); 97 } 98 99 void ThreadService::add_thread(JavaThread* thread, bool daemon) { 100 // Do not count VM internal or JVMTI agent threads 101 if (thread->is_hidden_from_external_view() || 102 thread->is_jvmti_agent_thread()) { 103 return; 104 } 105 106 _total_threads_count->inc(); 107 _live_threads_count->inc(); 108 109 if (_live_threads_count->get_value() > _peak_threads_count->get_value()) { 110 _peak_threads_count->set_value(_live_threads_count->get_value()); 111 } 112 113 if (daemon) { 114 _daemon_threads_count->inc(); 115 } 116 } 117 118 void ThreadService::remove_thread(JavaThread* thread, bool daemon) { 119 Atomic::dec((jint*) &_exiting_threads_count); 120 121 if (thread->is_hidden_from_external_view() || 122 thread->is_jvmti_agent_thread()) { 123 return; 124 } 125 126 _live_threads_count->set_value(_live_threads_count->get_value() - 1); 127 128 if (daemon) { 129 _daemon_threads_count->set_value(_daemon_threads_count->get_value() - 1); 130 Atomic::dec((jint*) &_exiting_daemon_threads_count); 131 } 132 } 133 134 void ThreadService::current_thread_exiting(JavaThread* jt) { 135 assert(jt == JavaThread::current(), "Called by current thread"); 136 Atomic::inc((jint*) &_exiting_threads_count); 137 138 oop threadObj = jt->threadObj(); 139 if (threadObj != NULL && java_lang_Thread::is_daemon(threadObj)) { 140 Atomic::inc((jint*) &_exiting_daemon_threads_count); 141 } 142 } 143 144 // FIXME: JVMTI should call this function 145 Handle ThreadService::get_current_contended_monitor(JavaThread* thread) { 146 assert(thread != NULL, "should be non-NULL"); 147 assert(Threads_lock->owned_by_self(), "must grab Threads_lock or be at safepoint"); 148 149 ObjectMonitor *wait_obj = thread->current_waiting_monitor(); 150 151 oop obj = NULL; 152 if (wait_obj != NULL) { 153 // thread is doing an Object.wait() call 154 obj = (oop) wait_obj->object(); 155 assert(obj != NULL, "Object.wait() should have an object"); 156 } else { 157 ObjectMonitor *enter_obj = thread->current_pending_monitor(); 158 if (enter_obj != NULL) { 159 // thread is trying to enter() or raw_enter() an ObjectMonitor. 160 obj = (oop) enter_obj->object(); 161 } 162 // If obj == NULL, then ObjectMonitor is raw which doesn't count. 163 } 164 165 Handle h(obj); 166 return h; 167 } 168 169 bool ThreadService::set_thread_monitoring_contention(bool flag) { 170 MutexLocker m(Management_lock); 171 172 bool prev = _thread_monitoring_contention_enabled; 173 _thread_monitoring_contention_enabled = flag; 174 175 return prev; 176 } 177 178 bool ThreadService::set_thread_cpu_time_enabled(bool flag) { 179 MutexLocker m(Management_lock); 180 181 bool prev = _thread_cpu_time_enabled; 182 _thread_cpu_time_enabled = flag; 183 184 return prev; 185 } 186 187 bool ThreadService::set_thread_allocated_memory_enabled(bool flag) { 188 MutexLocker m(Management_lock); 189 190 bool prev = _thread_allocated_memory_enabled; 191 _thread_allocated_memory_enabled = flag; 192 193 return prev; 194 } 195 196 // GC support 197 void ThreadService::oops_do(OopClosure* f) { 198 for (ThreadDumpResult* dump = _threaddump_list; dump != NULL; dump = dump->next()) { 199 dump->oops_do(f); 200 } 201 } 202 203 void ThreadService::add_thread_dump(ThreadDumpResult* dump) { 204 MutexLocker ml(Management_lock); 205 if (_threaddump_list == NULL) { 206 _threaddump_list = dump; 207 } else { 208 dump->set_next(_threaddump_list); 209 _threaddump_list = dump; 210 } 211 } 212 213 void ThreadService::remove_thread_dump(ThreadDumpResult* dump) { 214 MutexLocker ml(Management_lock); 215 216 ThreadDumpResult* prev = NULL; 217 bool found = false; 218 for (ThreadDumpResult* d = _threaddump_list; d != NULL; prev = d, d = d->next()) { 219 if (d == dump) { 220 if (prev == NULL) { 221 _threaddump_list = dump->next(); 222 } else { 223 prev->set_next(dump->next()); 224 } 225 found = true; 226 break; 227 } 228 } 229 assert(found, "The threaddump result to be removed must exist."); 230 } 231 232 // Dump stack trace of threads specified in the given threads array. 233 // Returns StackTraceElement[][] each element is the stack trace of a thread in 234 // the corresponding entry in the given threads array 235 Handle ThreadService::dump_stack_traces(GrowableArray<instanceHandle>* threads, 236 int num_threads, 237 TRAPS) { 238 assert(num_threads > 0, "just checking"); 239 240 ThreadDumpResult dump_result; 241 VM_ThreadDump op(&dump_result, 242 threads, 243 num_threads, 244 -1, /* entire stack */ 245 false, /* with locked monitors */ 246 false /* with locked synchronizers */); 247 VMThread::execute(&op); 248 249 // Allocate the resulting StackTraceElement[][] object 250 251 ResourceMark rm(THREAD); 252 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackTraceElement_array(), true, CHECK_NH); 253 ObjArrayKlass* ik = ObjArrayKlass::cast(k); 254 objArrayOop r = oopFactory::new_objArray(ik, num_threads, CHECK_NH); 255 objArrayHandle result_obj(THREAD, r); 256 257 int num_snapshots = dump_result.num_snapshots(); 258 assert(num_snapshots == num_threads, "Must have num_threads thread snapshots"); 259 int i = 0; 260 for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; i++, ts = ts->next()) { 261 ThreadStackTrace* stacktrace = ts->get_stack_trace(); 262 if (stacktrace == NULL) { 263 // No stack trace 264 result_obj->obj_at_put(i, NULL); 265 } else { 266 // Construct an array of java/lang/StackTraceElement object 267 Handle backtrace_h = stacktrace->allocate_fill_stack_trace_element_array(CHECK_NH); 268 result_obj->obj_at_put(i, backtrace_h()); 269 } 270 } 271 272 return result_obj; 273 } 274 275 void ThreadService::reset_contention_count_stat(JavaThread* thread) { 276 ThreadStatistics* stat = thread->get_thread_stat(); 277 if (stat != NULL) { 278 stat->reset_count_stat(); 279 } 280 } 281 282 void ThreadService::reset_contention_time_stat(JavaThread* thread) { 283 ThreadStatistics* stat = thread->get_thread_stat(); 284 if (stat != NULL) { 285 stat->reset_time_stat(); 286 } 287 } 288 289 // Find deadlocks involving object monitors and concurrent locks if concurrent_locks is true 290 DeadlockCycle* ThreadService::find_deadlocks_at_safepoint(bool concurrent_locks) { 291 // This code was modified from the original Threads::find_deadlocks code. 292 int globalDfn = 0, thisDfn; 293 ObjectMonitor* waitingToLockMonitor = NULL; 294 oop waitingToLockBlocker = NULL; 295 bool blocked_on_monitor = false; 296 JavaThread *currentThread, *previousThread; 297 int num_deadlocks = 0; 298 299 for (JavaThread* p = Threads::first(); p != NULL; p = p->next()) { 300 // Initialize the depth-first-number 301 p->set_depth_first_number(-1); 302 } 303 304 DeadlockCycle* deadlocks = NULL; 305 DeadlockCycle* last = NULL; 306 DeadlockCycle* cycle = new DeadlockCycle(); 307 for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) { 308 if (jt->depth_first_number() >= 0) { 309 // this thread was already visited 310 continue; 311 } 312 313 thisDfn = globalDfn; 314 jt->set_depth_first_number(globalDfn++); 315 previousThread = jt; 316 currentThread = jt; 317 318 cycle->reset(); 319 320 // When there is a deadlock, all the monitors involved in the dependency 321 // cycle must be contended and heavyweight. So we only care about the 322 // heavyweight monitor a thread is waiting to lock. 323 waitingToLockMonitor = (ObjectMonitor*)jt->current_pending_monitor(); 324 if (concurrent_locks) { 325 waitingToLockBlocker = jt->current_park_blocker(); 326 } 327 while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) { 328 cycle->add_thread(currentThread); 329 if (waitingToLockMonitor != NULL) { 330 currentThread = Threads::owning_thread_from_monitor_owner((address)waitingToLockMonitor->owner(), 331 false /* no locking needed */); 332 } else { 333 if (concurrent_locks) { 334 if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) { 335 oop threadObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker); 336 currentThread = threadObj != NULL ? java_lang_Thread::thread(threadObj) : NULL; 337 } else { 338 currentThread = NULL; 339 } 340 } 341 } 342 343 if (currentThread == NULL) { 344 // No dependency on another thread 345 break; 346 } 347 if (currentThread->depth_first_number() < 0) { 348 // First visit to this thread 349 currentThread->set_depth_first_number(globalDfn++); 350 } else if (currentThread->depth_first_number() < thisDfn) { 351 // Thread already visited, and not on a (new) cycle 352 break; 353 } else if (currentThread == previousThread) { 354 // Self-loop, ignore 355 break; 356 } else { 357 // We have a (new) cycle 358 num_deadlocks++; 359 360 cycle->set_deadlock(true); 361 362 // add this cycle to the deadlocks list 363 if (deadlocks == NULL) { 364 deadlocks = cycle; 365 } else { 366 last->set_next(cycle); 367 } 368 last = cycle; 369 cycle = new DeadlockCycle(); 370 break; 371 } 372 previousThread = currentThread; 373 waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor(); 374 if (concurrent_locks) { 375 waitingToLockBlocker = currentThread->current_park_blocker(); 376 } 377 } 378 379 } 380 delete cycle; 381 return deadlocks; 382 } 383 384 ThreadDumpResult::ThreadDumpResult() : _num_threads(0), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) { 385 386 // Create a new ThreadDumpResult object and append to the list. 387 // If GC happens before this function returns, Method* 388 // in the stack trace will be visited. 389 ThreadService::add_thread_dump(this); 390 } 391 392 ThreadDumpResult::ThreadDumpResult(int num_threads) : _num_threads(num_threads), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) { 393 // Create a new ThreadDumpResult object and append to the list. 394 // If GC happens before this function returns, oops 395 // will be visited. 396 ThreadService::add_thread_dump(this); 397 } 398 399 ThreadDumpResult::~ThreadDumpResult() { 400 ThreadService::remove_thread_dump(this); 401 402 // free all the ThreadSnapshot objects created during 403 // the VM_ThreadDump operation 404 ThreadSnapshot* ts = _snapshots; 405 while (ts != NULL) { 406 ThreadSnapshot* p = ts; 407 ts = ts->next(); 408 delete p; 409 } 410 } 411 412 413 void ThreadDumpResult::add_thread_snapshot(ThreadSnapshot* ts) { 414 assert(_num_threads == 0 || _num_snapshots < _num_threads, 415 "_num_snapshots must be less than _num_threads"); 416 _num_snapshots++; 417 if (_snapshots == NULL) { 418 _snapshots = ts; 419 } else { 420 _last->set_next(ts); 421 } 422 _last = ts; 423 } 424 425 void ThreadDumpResult::oops_do(OopClosure* f) { 426 for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) { 427 ts->oops_do(f); 428 } 429 } 430 431 StackFrameInfo::StackFrameInfo(javaVFrame* jvf, bool with_lock_info) { 432 _method = jvf->method(); 433 _bci = jvf->bci(); 434 _locked_monitors = NULL; 435 if (with_lock_info) { 436 ResourceMark rm; 437 GrowableArray<MonitorInfo*>* list = jvf->locked_monitors(); 438 int length = list->length(); 439 if (length > 0) { 440 _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true); 441 for (int i = 0; i < length; i++) { 442 MonitorInfo* monitor = list->at(i); 443 assert(monitor->owner(), "This monitor must have an owning object"); 444 _locked_monitors->append(monitor->owner()); 445 } 446 } 447 } 448 } 449 450 void StackFrameInfo::oops_do(OopClosure* f) { 451 if (_locked_monitors != NULL) { 452 int length = _locked_monitors->length(); 453 for (int i = 0; i < length; i++) { 454 f->do_oop((oop*) _locked_monitors->adr_at(i)); 455 } 456 } 457 } 458 459 void StackFrameInfo::print_on(outputStream* st) const { 460 ResourceMark rm; 461 java_lang_Throwable::print_stack_element(st, method(), bci()); 462 int len = (_locked_monitors != NULL ? _locked_monitors->length() : 0); 463 for (int i = 0; i < len; i++) { 464 oop o = _locked_monitors->at(i); 465 InstanceKlass* ik = InstanceKlass::cast(o->klass()); 466 st->print_cr("\t- locked <" INTPTR_FORMAT "> (a %s)", (address)o, ik->external_name()); 467 } 468 469 } 470 471 // Iterate through monitor cache to find JNI locked monitors 472 class InflatedMonitorsClosure: public MonitorClosure { 473 private: 474 ThreadStackTrace* _stack_trace; 475 Thread* _thread; 476 public: 477 InflatedMonitorsClosure(Thread* t, ThreadStackTrace* st) { 478 _thread = t; 479 _stack_trace = st; 480 } 481 void do_monitor(ObjectMonitor* mid) { 482 if (mid->owner() == _thread) { 483 oop object = (oop) mid->object(); 484 if (!_stack_trace->is_owned_monitor_on_stack(object)) { 485 _stack_trace->add_jni_locked_monitor(object); 486 } 487 } 488 } 489 }; 490 491 ThreadStackTrace::ThreadStackTrace(JavaThread* t, bool with_locked_monitors) { 492 _thread = t; 493 _frames = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<StackFrameInfo*>(INITIAL_ARRAY_SIZE, true); 494 _depth = 0; 495 _with_locked_monitors = with_locked_monitors; 496 if (_with_locked_monitors) { 497 _jni_locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true); 498 } else { 499 _jni_locked_monitors = NULL; 500 } 501 } 502 503 ThreadStackTrace::~ThreadStackTrace() { 504 for (int i = 0; i < _frames->length(); i++) { 505 delete _frames->at(i); 506 } 507 delete _frames; 508 if (_jni_locked_monitors != NULL) { 509 delete _jni_locked_monitors; 510 } 511 } 512 513 void ThreadStackTrace::dump_stack_at_safepoint(int maxDepth) { 514 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 515 516 if (_thread->has_last_Java_frame()) { 517 RegisterMap reg_map(_thread); 518 vframe* start_vf = _thread->last_java_vframe(®_map); 519 int count = 0; 520 for (vframe* f = start_vf; f; f = f->sender() ) { 521 if (f->is_java_frame()) { 522 javaVFrame* jvf = javaVFrame::cast(f); 523 add_stack_frame(jvf); 524 count++; 525 } else { 526 // Ignore non-Java frames 527 } 528 if (maxDepth > 0 && count == maxDepth) { 529 // Skip frames if more than maxDepth 530 break; 531 } 532 } 533 } 534 535 if (_with_locked_monitors) { 536 // Iterate inflated monitors and find monitors locked by this thread 537 // not found in the stack 538 InflatedMonitorsClosure imc(_thread, this); 539 ObjectSynchronizer::monitors_iterate(&imc); 540 } 541 } 542 543 544 bool ThreadStackTrace::is_owned_monitor_on_stack(oop object) { 545 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 546 547 bool found = false; 548 int num_frames = get_stack_depth(); 549 for (int depth = 0; depth < num_frames; depth++) { 550 StackFrameInfo* frame = stack_frame_at(depth); 551 int len = frame->num_locked_monitors(); 552 GrowableArray<oop>* locked_monitors = frame->locked_monitors(); 553 for (int j = 0; j < len; j++) { 554 oop monitor = locked_monitors->at(j); 555 assert(monitor != NULL && monitor->is_instance(), "must be a Java object"); 556 if (monitor == object) { 557 found = true; 558 break; 559 } 560 } 561 } 562 return found; 563 } 564 565 Handle ThreadStackTrace::allocate_fill_stack_trace_element_array(TRAPS) { 566 Klass* k = SystemDictionary::StackTraceElement_klass(); 567 assert(k != NULL, "must be loaded in 1.4+"); 568 instanceKlassHandle ik(THREAD, k); 569 570 // Allocate an array of java/lang/StackTraceElement object 571 objArrayOop ste = oopFactory::new_objArray(ik(), _depth, CHECK_NH); 572 objArrayHandle backtrace(THREAD, ste); 573 for (int j = 0; j < _depth; j++) { 574 StackFrameInfo* frame = _frames->at(j); 575 methodHandle mh(THREAD, frame->method()); 576 oop element = java_lang_StackTraceElement::create(mh, frame->bci(), CHECK_NH); 577 backtrace->obj_at_put(j, element); 578 } 579 return backtrace; 580 } 581 582 void ThreadStackTrace::add_stack_frame(javaVFrame* jvf) { 583 StackFrameInfo* frame = new StackFrameInfo(jvf, _with_locked_monitors); 584 _frames->append(frame); 585 _depth++; 586 } 587 588 void ThreadStackTrace::oops_do(OopClosure* f) { 589 int length = _frames->length(); 590 for (int i = 0; i < length; i++) { 591 _frames->at(i)->oops_do(f); 592 } 593 594 length = (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0); 595 for (int j = 0; j < length; j++) { 596 f->do_oop((oop*) _jni_locked_monitors->adr_at(j)); 597 } 598 } 599 600 ConcurrentLocksDump::~ConcurrentLocksDump() { 601 if (_retain_map_on_free) { 602 return; 603 } 604 605 for (ThreadConcurrentLocks* t = _map; t != NULL;) { 606 ThreadConcurrentLocks* tcl = t; 607 t = t->next(); 608 delete tcl; 609 } 610 } 611 612 void ConcurrentLocksDump::dump_at_safepoint() { 613 // dump all locked concurrent locks 614 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped"); 615 616 if (JDK_Version::is_gte_jdk16x_version()) { 617 ResourceMark rm; 618 619 GrowableArray<oop>* aos_objects = new GrowableArray<oop>(INITIAL_ARRAY_SIZE); 620 621 // Find all instances of AbstractOwnableSynchronizer 622 HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(), 623 aos_objects); 624 // Build a map of thread to its owned AQS locks 625 build_map(aos_objects); 626 } 627 } 628 629 630 // build a map of JavaThread to all its owned AbstractOwnableSynchronizer 631 void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) { 632 int length = aos_objects->length(); 633 for (int i = 0; i < length; i++) { 634 oop o = aos_objects->at(i); 635 oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o); 636 if (owner_thread_obj != NULL) { 637 JavaThread* thread = java_lang_Thread::thread(owner_thread_obj); 638 assert(o->is_instance(), "Must be an instanceOop"); 639 add_lock(thread, (instanceOop) o); 640 } 641 } 642 } 643 644 void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) { 645 ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread); 646 if (tcl != NULL) { 647 tcl->add_lock(o); 648 return; 649 } 650 651 // First owned lock found for this thread 652 tcl = new ThreadConcurrentLocks(thread); 653 tcl->add_lock(o); 654 if (_map == NULL) { 655 _map = tcl; 656 } else { 657 _last->set_next(tcl); 658 } 659 _last = tcl; 660 } 661 662 ThreadConcurrentLocks* ConcurrentLocksDump::thread_concurrent_locks(JavaThread* thread) { 663 for (ThreadConcurrentLocks* tcl = _map; tcl != NULL; tcl = tcl->next()) { 664 if (tcl->java_thread() == thread) { 665 return tcl; 666 } 667 } 668 return NULL; 669 } 670 671 void ConcurrentLocksDump::print_locks_on(JavaThread* t, outputStream* st) { 672 st->print_cr(" Locked ownable synchronizers:"); 673 ThreadConcurrentLocks* tcl = thread_concurrent_locks(t); 674 GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL); 675 if (locks == NULL || locks->is_empty()) { 676 st->print_cr("\t- None"); 677 st->cr(); 678 return; 679 } 680 681 for (int i = 0; i < locks->length(); i++) { 682 instanceOop obj = locks->at(i); 683 InstanceKlass* ik = InstanceKlass::cast(obj->klass()); 684 st->print_cr("\t- <" INTPTR_FORMAT "> (a %s)", (address)obj, ik->external_name()); 685 } 686 st->cr(); 687 } 688 689 ThreadConcurrentLocks::ThreadConcurrentLocks(JavaThread* thread) { 690 _thread = thread; 691 _owned_locks = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<instanceOop>(INITIAL_ARRAY_SIZE, true); 692 _next = NULL; 693 } 694 695 ThreadConcurrentLocks::~ThreadConcurrentLocks() { 696 delete _owned_locks; 697 } 698 699 void ThreadConcurrentLocks::add_lock(instanceOop o) { 700 _owned_locks->append(o); 701 } 702 703 void ThreadConcurrentLocks::oops_do(OopClosure* f) { 704 int length = _owned_locks->length(); 705 for (int i = 0; i < length; i++) { 706 f->do_oop((oop*) _owned_locks->adr_at(i)); 707 } 708 } 709 710 ThreadStatistics::ThreadStatistics() { 711 _contended_enter_count = 0; 712 _monitor_wait_count = 0; 713 _sleep_count = 0; 714 _count_pending_reset = false; 715 _timer_pending_reset = false; 716 memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts)); 717 } 718 719 ThreadSnapshot::ThreadSnapshot(JavaThread* thread) { 720 _thread = thread; 721 _threadObj = thread->threadObj(); 722 _stack_trace = NULL; 723 _concurrent_locks = NULL; 724 _next = NULL; 725 726 ThreadStatistics* stat = thread->get_thread_stat(); 727 _contended_enter_ticks = stat->contended_enter_ticks(); 728 _contended_enter_count = stat->contended_enter_count(); 729 _monitor_wait_ticks = stat->monitor_wait_ticks(); 730 _monitor_wait_count = stat->monitor_wait_count(); 731 _sleep_ticks = stat->sleep_ticks(); 732 _sleep_count = stat->sleep_count(); 733 734 _blocker_object = NULL; 735 _blocker_object_owner = NULL; 736 737 _thread_status = java_lang_Thread::get_thread_status(_threadObj); 738 _is_ext_suspended = thread->is_being_ext_suspended(); 739 _is_in_native = (thread->thread_state() == _thread_in_native); 740 741 if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER || 742 _thread_status == java_lang_Thread::IN_OBJECT_WAIT || 743 _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) { 744 745 Handle obj = ThreadService::get_current_contended_monitor(thread); 746 if (obj() == NULL) { 747 // monitor no longer exists; thread is not blocked 748 _thread_status = java_lang_Thread::RUNNABLE; 749 } else { 750 _blocker_object = obj(); 751 JavaThread* owner = ObjectSynchronizer::get_lock_owner(obj, false); 752 if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER) 753 || (owner != NULL && owner->is_attaching_via_jni())) { 754 // ownership information of the monitor is not available 755 // (may no longer be owned or releasing to some other thread) 756 // make this thread in RUNNABLE state. 757 // And when the owner thread is in attaching state, the java thread 758 // is not completely initialized. For example thread name and id 759 // and may not be set, so hide the attaching thread. 760 _thread_status = java_lang_Thread::RUNNABLE; 761 _blocker_object = NULL; 762 } else if (owner != NULL) { 763 _blocker_object_owner = owner->threadObj(); 764 } 765 } 766 } 767 768 // Support for JSR-166 locks 769 if (JDK_Version::current().supports_thread_park_blocker() && 770 (_thread_status == java_lang_Thread::PARKED || 771 _thread_status == java_lang_Thread::PARKED_TIMED)) { 772 773 _blocker_object = thread->current_park_blocker(); 774 if (_blocker_object != NULL && _blocker_object->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) { 775 _blocker_object_owner = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(_blocker_object); 776 } 777 } 778 } 779 780 ThreadSnapshot::~ThreadSnapshot() { 781 delete _stack_trace; 782 delete _concurrent_locks; 783 } 784 785 void ThreadSnapshot::dump_stack_at_safepoint(int max_depth, bool with_locked_monitors) { 786 _stack_trace = new ThreadStackTrace(_thread, with_locked_monitors); 787 _stack_trace->dump_stack_at_safepoint(max_depth); 788 } 789 790 791 void ThreadSnapshot::oops_do(OopClosure* f) { 792 f->do_oop(&_threadObj); 793 f->do_oop(&_blocker_object); 794 f->do_oop(&_blocker_object_owner); 795 if (_stack_trace != NULL) { 796 _stack_trace->oops_do(f); 797 } 798 if (_concurrent_locks != NULL) { 799 _concurrent_locks->oops_do(f); 800 } 801 } 802 803 DeadlockCycle::DeadlockCycle() { 804 _is_deadlock = false; 805 _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true); 806 _next = NULL; 807 } 808 809 DeadlockCycle::~DeadlockCycle() { 810 delete _threads; 811 } 812 813 void DeadlockCycle::print_on(outputStream* st) const { 814 st->cr(); 815 st->print_cr("Found one Java-level deadlock:"); 816 st->print("============================="); 817 818 JavaThread* currentThread; 819 ObjectMonitor* waitingToLockMonitor; 820 oop waitingToLockBlocker; 821 int len = _threads->length(); 822 for (int i = 0; i < len; i++) { 823 currentThread = _threads->at(i); 824 waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor(); 825 waitingToLockBlocker = currentThread->current_park_blocker(); 826 st->cr(); 827 st->print_cr("\"%s\":", currentThread->get_thread_name()); 828 const char* owner_desc = ",\n which is held by"; 829 if (waitingToLockMonitor != NULL) { 830 st->print(" waiting to lock monitor " INTPTR_FORMAT, waitingToLockMonitor); 831 oop obj = (oop)waitingToLockMonitor->object(); 832 if (obj != NULL) { 833 st->print(" (object "INTPTR_FORMAT ", a %s)", (address)obj, 834 (InstanceKlass::cast(obj->klass()))->external_name()); 835 836 if (!currentThread->current_pending_monitor_is_from_java()) { 837 owner_desc = "\n in JNI, which is held by"; 838 } 839 } else { 840 // No Java object associated - a JVMTI raw monitor 841 owner_desc = " (JVMTI raw monitor),\n which is held by"; 842 } 843 currentThread = Threads::owning_thread_from_monitor_owner( 844 (address)waitingToLockMonitor->owner(), false /* no locking needed */); 845 } else { 846 st->print(" waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)", 847 (address)waitingToLockBlocker, 848 (InstanceKlass::cast(waitingToLockBlocker->klass()))->external_name()); 849 assert(waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass()), 850 "Must be an AbstractOwnableSynchronizer"); 851 oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker); 852 currentThread = java_lang_Thread::thread(ownerObj); 853 } 854 st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name()); 855 } 856 857 st->cr(); 858 st->cr(); 859 860 // Print stack traces 861 bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace; 862 JavaMonitorsInStackTrace = true; 863 st->print_cr("Java stack information for the threads listed above:"); 864 st->print_cr("==================================================="); 865 for (int j = 0; j < len; j++) { 866 currentThread = _threads->at(j); 867 st->print_cr("\"%s\":", currentThread->get_thread_name()); 868 currentThread->print_stack_on(st); 869 } 870 JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace; 871 } 872 873 ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread, 874 bool include_jvmti_agent_threads, 875 bool include_jni_attaching_threads) { 876 assert(cur_thread == Thread::current(), "Check current thread"); 877 878 int init_size = ThreadService::get_live_thread_count(); 879 _threads_array = new GrowableArray<instanceHandle>(init_size); 880 881 MutexLockerEx ml(Threads_lock); 882 883 for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) { 884 // skips JavaThreads in the process of exiting 885 // and also skips VM internal JavaThreads 886 // Threads in _thread_new or _thread_new_trans state are included. 887 // i.e. threads have been started but not yet running. 888 if (jt->threadObj() == NULL || 889 jt->is_exiting() || 890 !java_lang_Thread::is_alive(jt->threadObj()) || 891 jt->is_hidden_from_external_view()) { 892 continue; 893 } 894 895 // skip agent threads 896 if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) { 897 continue; 898 } 899 900 // skip jni threads in the process of attaching 901 if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) { 902 continue; 903 } 904 905 instanceHandle h(cur_thread, (instanceOop) jt->threadObj()); 906 _threads_array->append(h); 907 } 908 }