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