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