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