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