Mon, 31 Mar 2014 13:09:35 -0700
7090324: gclog rotation via external tool
Summary: GC log rotation can be set via java command line, but customer sometime need to sync with OS level rotation setting.
Reviewed-by: sla, minqi, ehelin
Contributed-by: suenaga.yasumasa@lab.ntt.co.jp
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::metadata_do(void f(Metadata*)) {
204 for (ThreadDumpResult* dump = _threaddump_list; dump != NULL; dump = dump->next()) {
205 dump->metadata_do(f);
206 }
207 }
209 void ThreadService::add_thread_dump(ThreadDumpResult* dump) {
210 MutexLocker ml(Management_lock);
211 if (_threaddump_list == NULL) {
212 _threaddump_list = dump;
213 } else {
214 dump->set_next(_threaddump_list);
215 _threaddump_list = dump;
216 }
217 }
219 void ThreadService::remove_thread_dump(ThreadDumpResult* dump) {
220 MutexLocker ml(Management_lock);
222 ThreadDumpResult* prev = NULL;
223 bool found = false;
224 for (ThreadDumpResult* d = _threaddump_list; d != NULL; prev = d, d = d->next()) {
225 if (d == dump) {
226 if (prev == NULL) {
227 _threaddump_list = dump->next();
228 } else {
229 prev->set_next(dump->next());
230 }
231 found = true;
232 break;
233 }
234 }
235 assert(found, "The threaddump result to be removed must exist.");
236 }
238 // Dump stack trace of threads specified in the given threads array.
239 // Returns StackTraceElement[][] each element is the stack trace of a thread in
240 // the corresponding entry in the given threads array
241 Handle ThreadService::dump_stack_traces(GrowableArray<instanceHandle>* threads,
242 int num_threads,
243 TRAPS) {
244 assert(num_threads > 0, "just checking");
246 ThreadDumpResult dump_result;
247 VM_ThreadDump op(&dump_result,
248 threads,
249 num_threads,
250 -1, /* entire stack */
251 false, /* with locked monitors */
252 false /* with locked synchronizers */);
253 VMThread::execute(&op);
255 // Allocate the resulting StackTraceElement[][] object
257 ResourceMark rm(THREAD);
258 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackTraceElement_array(), true, CHECK_NH);
259 ObjArrayKlass* ik = ObjArrayKlass::cast(k);
260 objArrayOop r = oopFactory::new_objArray(ik, num_threads, CHECK_NH);
261 objArrayHandle result_obj(THREAD, r);
263 int num_snapshots = dump_result.num_snapshots();
264 assert(num_snapshots == num_threads, "Must have num_threads thread snapshots");
265 int i = 0;
266 for (ThreadSnapshot* ts = dump_result.snapshots(); ts != NULL; i++, ts = ts->next()) {
267 ThreadStackTrace* stacktrace = ts->get_stack_trace();
268 if (stacktrace == NULL) {
269 // No stack trace
270 result_obj->obj_at_put(i, NULL);
271 } else {
272 // Construct an array of java/lang/StackTraceElement object
273 Handle backtrace_h = stacktrace->allocate_fill_stack_trace_element_array(CHECK_NH);
274 result_obj->obj_at_put(i, backtrace_h());
275 }
276 }
278 return result_obj;
279 }
281 void ThreadService::reset_contention_count_stat(JavaThread* thread) {
282 ThreadStatistics* stat = thread->get_thread_stat();
283 if (stat != NULL) {
284 stat->reset_count_stat();
285 }
286 }
288 void ThreadService::reset_contention_time_stat(JavaThread* thread) {
289 ThreadStatistics* stat = thread->get_thread_stat();
290 if (stat != NULL) {
291 stat->reset_time_stat();
292 }
293 }
295 // Find deadlocks involving object monitors and concurrent locks if concurrent_locks is true
296 DeadlockCycle* ThreadService::find_deadlocks_at_safepoint(bool concurrent_locks) {
297 // This code was modified from the original Threads::find_deadlocks code.
298 int globalDfn = 0, thisDfn;
299 ObjectMonitor* waitingToLockMonitor = NULL;
300 oop waitingToLockBlocker = NULL;
301 bool blocked_on_monitor = false;
302 JavaThread *currentThread, *previousThread;
303 int num_deadlocks = 0;
305 for (JavaThread* p = Threads::first(); p != NULL; p = p->next()) {
306 // Initialize the depth-first-number
307 p->set_depth_first_number(-1);
308 }
310 DeadlockCycle* deadlocks = NULL;
311 DeadlockCycle* last = NULL;
312 DeadlockCycle* cycle = new DeadlockCycle();
313 for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
314 if (jt->depth_first_number() >= 0) {
315 // this thread was already visited
316 continue;
317 }
319 thisDfn = globalDfn;
320 jt->set_depth_first_number(globalDfn++);
321 previousThread = jt;
322 currentThread = jt;
324 cycle->reset();
326 // When there is a deadlock, all the monitors involved in the dependency
327 // cycle must be contended and heavyweight. So we only care about the
328 // heavyweight monitor a thread is waiting to lock.
329 waitingToLockMonitor = (ObjectMonitor*)jt->current_pending_monitor();
330 if (concurrent_locks) {
331 waitingToLockBlocker = jt->current_park_blocker();
332 }
333 while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) {
334 cycle->add_thread(currentThread);
335 if (waitingToLockMonitor != NULL) {
336 address currentOwner = (address)waitingToLockMonitor->owner();
337 if (currentOwner != NULL) {
338 currentThread = Threads::owning_thread_from_monitor_owner(
339 currentOwner,
340 false /* no locking needed */);
341 if (currentThread == NULL) {
342 // This function is called at a safepoint so the JavaThread
343 // that owns waitingToLockMonitor should be findable, but
344 // if it is not findable, then the previous currentThread is
345 // blocked permanently. We record this as a deadlock.
346 num_deadlocks++;
348 cycle->set_deadlock(true);
350 // add this cycle to the deadlocks list
351 if (deadlocks == NULL) {
352 deadlocks = cycle;
353 } else {
354 last->set_next(cycle);
355 }
356 last = cycle;
357 cycle = new DeadlockCycle();
358 break;
359 }
360 }
361 } else {
362 if (concurrent_locks) {
363 if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
364 oop threadObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
365 currentThread = threadObj != NULL ? java_lang_Thread::thread(threadObj) : NULL;
366 } else {
367 currentThread = NULL;
368 }
369 }
370 }
372 if (currentThread == NULL) {
373 // No dependency on another thread
374 break;
375 }
376 if (currentThread->depth_first_number() < 0) {
377 // First visit to this thread
378 currentThread->set_depth_first_number(globalDfn++);
379 } else if (currentThread->depth_first_number() < thisDfn) {
380 // Thread already visited, and not on a (new) cycle
381 break;
382 } else if (currentThread == previousThread) {
383 // Self-loop, ignore
384 break;
385 } else {
386 // We have a (new) cycle
387 num_deadlocks++;
389 cycle->set_deadlock(true);
391 // add this cycle to the deadlocks list
392 if (deadlocks == NULL) {
393 deadlocks = cycle;
394 } else {
395 last->set_next(cycle);
396 }
397 last = cycle;
398 cycle = new DeadlockCycle();
399 break;
400 }
401 previousThread = currentThread;
402 waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
403 if (concurrent_locks) {
404 waitingToLockBlocker = currentThread->current_park_blocker();
405 }
406 }
408 }
409 delete cycle;
410 return deadlocks;
411 }
413 ThreadDumpResult::ThreadDumpResult() : _num_threads(0), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
415 // Create a new ThreadDumpResult object and append to the list.
416 // If GC happens before this function returns, Method*
417 // in the stack trace will be visited.
418 ThreadService::add_thread_dump(this);
419 }
421 ThreadDumpResult::ThreadDumpResult(int num_threads) : _num_threads(num_threads), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
422 // Create a new ThreadDumpResult object and append to the list.
423 // If GC happens before this function returns, oops
424 // will be visited.
425 ThreadService::add_thread_dump(this);
426 }
428 ThreadDumpResult::~ThreadDumpResult() {
429 ThreadService::remove_thread_dump(this);
431 // free all the ThreadSnapshot objects created during
432 // the VM_ThreadDump operation
433 ThreadSnapshot* ts = _snapshots;
434 while (ts != NULL) {
435 ThreadSnapshot* p = ts;
436 ts = ts->next();
437 delete p;
438 }
439 }
442 void ThreadDumpResult::add_thread_snapshot(ThreadSnapshot* ts) {
443 assert(_num_threads == 0 || _num_snapshots < _num_threads,
444 "_num_snapshots must be less than _num_threads");
445 _num_snapshots++;
446 if (_snapshots == NULL) {
447 _snapshots = ts;
448 } else {
449 _last->set_next(ts);
450 }
451 _last = ts;
452 }
454 void ThreadDumpResult::oops_do(OopClosure* f) {
455 for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
456 ts->oops_do(f);
457 }
458 }
460 void ThreadDumpResult::metadata_do(void f(Metadata*)) {
461 for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
462 ts->metadata_do(f);
463 }
464 }
466 StackFrameInfo::StackFrameInfo(javaVFrame* jvf, bool with_lock_info) {
467 _method = jvf->method();
468 _bci = jvf->bci();
469 _class_holder = _method->method_holder()->klass_holder();
470 _locked_monitors = NULL;
471 if (with_lock_info) {
472 ResourceMark rm;
473 GrowableArray<MonitorInfo*>* list = jvf->locked_monitors();
474 int length = list->length();
475 if (length > 0) {
476 _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true);
477 for (int i = 0; i < length; i++) {
478 MonitorInfo* monitor = list->at(i);
479 assert(monitor->owner(), "This monitor must have an owning object");
480 _locked_monitors->append(monitor->owner());
481 }
482 }
483 }
484 }
486 void StackFrameInfo::oops_do(OopClosure* f) {
487 if (_locked_monitors != NULL) {
488 int length = _locked_monitors->length();
489 for (int i = 0; i < length; i++) {
490 f->do_oop((oop*) _locked_monitors->adr_at(i));
491 }
492 }
493 f->do_oop(&_class_holder);
494 }
496 void StackFrameInfo::metadata_do(void f(Metadata*)) {
497 f(_method);
498 }
500 void StackFrameInfo::print_on(outputStream* st) const {
501 ResourceMark rm;
502 java_lang_Throwable::print_stack_element(st, method(), bci());
503 int len = (_locked_monitors != NULL ? _locked_monitors->length() : 0);
504 for (int i = 0; i < len; i++) {
505 oop o = _locked_monitors->at(i);
506 InstanceKlass* ik = InstanceKlass::cast(o->klass());
507 st->print_cr("\t- locked <" INTPTR_FORMAT "> (a %s)", (address)o, ik->external_name());
508 }
510 }
512 // Iterate through monitor cache to find JNI locked monitors
513 class InflatedMonitorsClosure: public MonitorClosure {
514 private:
515 ThreadStackTrace* _stack_trace;
516 Thread* _thread;
517 public:
518 InflatedMonitorsClosure(Thread* t, ThreadStackTrace* st) {
519 _thread = t;
520 _stack_trace = st;
521 }
522 void do_monitor(ObjectMonitor* mid) {
523 if (mid->owner() == _thread) {
524 oop object = (oop) mid->object();
525 if (!_stack_trace->is_owned_monitor_on_stack(object)) {
526 _stack_trace->add_jni_locked_monitor(object);
527 }
528 }
529 }
530 };
532 ThreadStackTrace::ThreadStackTrace(JavaThread* t, bool with_locked_monitors) {
533 _thread = t;
534 _frames = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<StackFrameInfo*>(INITIAL_ARRAY_SIZE, true);
535 _depth = 0;
536 _with_locked_monitors = with_locked_monitors;
537 if (_with_locked_monitors) {
538 _jni_locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true);
539 } else {
540 _jni_locked_monitors = NULL;
541 }
542 }
544 ThreadStackTrace::~ThreadStackTrace() {
545 for (int i = 0; i < _frames->length(); i++) {
546 delete _frames->at(i);
547 }
548 delete _frames;
549 if (_jni_locked_monitors != NULL) {
550 delete _jni_locked_monitors;
551 }
552 }
554 void ThreadStackTrace::dump_stack_at_safepoint(int maxDepth) {
555 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
557 if (_thread->has_last_Java_frame()) {
558 RegisterMap reg_map(_thread);
559 vframe* start_vf = _thread->last_java_vframe(®_map);
560 int count = 0;
561 for (vframe* f = start_vf; f; f = f->sender() ) {
562 if (f->is_java_frame()) {
563 javaVFrame* jvf = javaVFrame::cast(f);
564 add_stack_frame(jvf);
565 count++;
566 } else {
567 // Ignore non-Java frames
568 }
569 if (maxDepth > 0 && count == maxDepth) {
570 // Skip frames if more than maxDepth
571 break;
572 }
573 }
574 }
576 if (_with_locked_monitors) {
577 // Iterate inflated monitors and find monitors locked by this thread
578 // not found in the stack
579 InflatedMonitorsClosure imc(_thread, this);
580 ObjectSynchronizer::monitors_iterate(&imc);
581 }
582 }
585 bool ThreadStackTrace::is_owned_monitor_on_stack(oop object) {
586 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
588 bool found = false;
589 int num_frames = get_stack_depth();
590 for (int depth = 0; depth < num_frames; depth++) {
591 StackFrameInfo* frame = stack_frame_at(depth);
592 int len = frame->num_locked_monitors();
593 GrowableArray<oop>* locked_monitors = frame->locked_monitors();
594 for (int j = 0; j < len; j++) {
595 oop monitor = locked_monitors->at(j);
596 assert(monitor != NULL && monitor->is_instance(), "must be a Java object");
597 if (monitor == object) {
598 found = true;
599 break;
600 }
601 }
602 }
603 return found;
604 }
606 Handle ThreadStackTrace::allocate_fill_stack_trace_element_array(TRAPS) {
607 Klass* k = SystemDictionary::StackTraceElement_klass();
608 assert(k != NULL, "must be loaded in 1.4+");
609 instanceKlassHandle ik(THREAD, k);
611 // Allocate an array of java/lang/StackTraceElement object
612 objArrayOop ste = oopFactory::new_objArray(ik(), _depth, CHECK_NH);
613 objArrayHandle backtrace(THREAD, ste);
614 for (int j = 0; j < _depth; j++) {
615 StackFrameInfo* frame = _frames->at(j);
616 methodHandle mh(THREAD, frame->method());
617 oop element = java_lang_StackTraceElement::create(mh, frame->bci(), CHECK_NH);
618 backtrace->obj_at_put(j, element);
619 }
620 return backtrace;
621 }
623 void ThreadStackTrace::add_stack_frame(javaVFrame* jvf) {
624 StackFrameInfo* frame = new StackFrameInfo(jvf, _with_locked_monitors);
625 _frames->append(frame);
626 _depth++;
627 }
629 void ThreadStackTrace::oops_do(OopClosure* f) {
630 int length = _frames->length();
631 for (int i = 0; i < length; i++) {
632 _frames->at(i)->oops_do(f);
633 }
635 length = (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0);
636 for (int j = 0; j < length; j++) {
637 f->do_oop((oop*) _jni_locked_monitors->adr_at(j));
638 }
639 }
641 void ThreadStackTrace::metadata_do(void f(Metadata*)) {
642 int length = _frames->length();
643 for (int i = 0; i < length; i++) {
644 _frames->at(i)->metadata_do(f);
645 }
646 }
649 ConcurrentLocksDump::~ConcurrentLocksDump() {
650 if (_retain_map_on_free) {
651 return;
652 }
654 for (ThreadConcurrentLocks* t = _map; t != NULL;) {
655 ThreadConcurrentLocks* tcl = t;
656 t = t->next();
657 delete tcl;
658 }
659 }
661 void ConcurrentLocksDump::dump_at_safepoint() {
662 // dump all locked concurrent locks
663 assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
665 if (JDK_Version::is_gte_jdk16x_version()) {
666 ResourceMark rm;
668 GrowableArray<oop>* aos_objects = new GrowableArray<oop>(INITIAL_ARRAY_SIZE);
670 // Find all instances of AbstractOwnableSynchronizer
671 HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(),
672 aos_objects);
673 // Build a map of thread to its owned AQS locks
674 build_map(aos_objects);
675 }
676 }
679 // build a map of JavaThread to all its owned AbstractOwnableSynchronizer
680 void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) {
681 int length = aos_objects->length();
682 for (int i = 0; i < length; i++) {
683 oop o = aos_objects->at(i);
684 oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o);
685 if (owner_thread_obj != NULL) {
686 JavaThread* thread = java_lang_Thread::thread(owner_thread_obj);
687 assert(o->is_instance(), "Must be an instanceOop");
688 add_lock(thread, (instanceOop) o);
689 }
690 }
691 }
693 void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) {
694 ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread);
695 if (tcl != NULL) {
696 tcl->add_lock(o);
697 return;
698 }
700 // First owned lock found for this thread
701 tcl = new ThreadConcurrentLocks(thread);
702 tcl->add_lock(o);
703 if (_map == NULL) {
704 _map = tcl;
705 } else {
706 _last->set_next(tcl);
707 }
708 _last = tcl;
709 }
711 ThreadConcurrentLocks* ConcurrentLocksDump::thread_concurrent_locks(JavaThread* thread) {
712 for (ThreadConcurrentLocks* tcl = _map; tcl != NULL; tcl = tcl->next()) {
713 if (tcl->java_thread() == thread) {
714 return tcl;
715 }
716 }
717 return NULL;
718 }
720 void ConcurrentLocksDump::print_locks_on(JavaThread* t, outputStream* st) {
721 st->print_cr(" Locked ownable synchronizers:");
722 ThreadConcurrentLocks* tcl = thread_concurrent_locks(t);
723 GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL);
724 if (locks == NULL || locks->is_empty()) {
725 st->print_cr("\t- None");
726 st->cr();
727 return;
728 }
730 for (int i = 0; i < locks->length(); i++) {
731 instanceOop obj = locks->at(i);
732 InstanceKlass* ik = InstanceKlass::cast(obj->klass());
733 st->print_cr("\t- <" INTPTR_FORMAT "> (a %s)", (address)obj, ik->external_name());
734 }
735 st->cr();
736 }
738 ThreadConcurrentLocks::ThreadConcurrentLocks(JavaThread* thread) {
739 _thread = thread;
740 _owned_locks = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<instanceOop>(INITIAL_ARRAY_SIZE, true);
741 _next = NULL;
742 }
744 ThreadConcurrentLocks::~ThreadConcurrentLocks() {
745 delete _owned_locks;
746 }
748 void ThreadConcurrentLocks::add_lock(instanceOop o) {
749 _owned_locks->append(o);
750 }
752 void ThreadConcurrentLocks::oops_do(OopClosure* f) {
753 int length = _owned_locks->length();
754 for (int i = 0; i < length; i++) {
755 f->do_oop((oop*) _owned_locks->adr_at(i));
756 }
757 }
759 ThreadStatistics::ThreadStatistics() {
760 _contended_enter_count = 0;
761 _monitor_wait_count = 0;
762 _sleep_count = 0;
763 _count_pending_reset = false;
764 _timer_pending_reset = false;
765 memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts));
766 }
768 ThreadSnapshot::ThreadSnapshot(JavaThread* thread) {
769 _thread = thread;
770 _threadObj = thread->threadObj();
771 _stack_trace = NULL;
772 _concurrent_locks = NULL;
773 _next = NULL;
775 ThreadStatistics* stat = thread->get_thread_stat();
776 _contended_enter_ticks = stat->contended_enter_ticks();
777 _contended_enter_count = stat->contended_enter_count();
778 _monitor_wait_ticks = stat->monitor_wait_ticks();
779 _monitor_wait_count = stat->monitor_wait_count();
780 _sleep_ticks = stat->sleep_ticks();
781 _sleep_count = stat->sleep_count();
783 _blocker_object = NULL;
784 _blocker_object_owner = NULL;
786 _thread_status = java_lang_Thread::get_thread_status(_threadObj);
787 _is_ext_suspended = thread->is_being_ext_suspended();
788 _is_in_native = (thread->thread_state() == _thread_in_native);
790 if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER ||
791 _thread_status == java_lang_Thread::IN_OBJECT_WAIT ||
792 _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) {
794 Handle obj = ThreadService::get_current_contended_monitor(thread);
795 if (obj() == NULL) {
796 // monitor no longer exists; thread is not blocked
797 _thread_status = java_lang_Thread::RUNNABLE;
798 } else {
799 _blocker_object = obj();
800 JavaThread* owner = ObjectSynchronizer::get_lock_owner(obj, false);
801 if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER)
802 || (owner != NULL && owner->is_attaching_via_jni())) {
803 // ownership information of the monitor is not available
804 // (may no longer be owned or releasing to some other thread)
805 // make this thread in RUNNABLE state.
806 // And when the owner thread is in attaching state, the java thread
807 // is not completely initialized. For example thread name and id
808 // and may not be set, so hide the attaching thread.
809 _thread_status = java_lang_Thread::RUNNABLE;
810 _blocker_object = NULL;
811 } else if (owner != NULL) {
812 _blocker_object_owner = owner->threadObj();
813 }
814 }
815 }
817 // Support for JSR-166 locks
818 if (JDK_Version::current().supports_thread_park_blocker() &&
819 (_thread_status == java_lang_Thread::PARKED ||
820 _thread_status == java_lang_Thread::PARKED_TIMED)) {
822 _blocker_object = thread->current_park_blocker();
823 if (_blocker_object != NULL && _blocker_object->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
824 _blocker_object_owner = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(_blocker_object);
825 }
826 }
827 }
829 ThreadSnapshot::~ThreadSnapshot() {
830 delete _stack_trace;
831 delete _concurrent_locks;
832 }
834 void ThreadSnapshot::dump_stack_at_safepoint(int max_depth, bool with_locked_monitors) {
835 _stack_trace = new ThreadStackTrace(_thread, with_locked_monitors);
836 _stack_trace->dump_stack_at_safepoint(max_depth);
837 }
840 void ThreadSnapshot::oops_do(OopClosure* f) {
841 f->do_oop(&_threadObj);
842 f->do_oop(&_blocker_object);
843 f->do_oop(&_blocker_object_owner);
844 if (_stack_trace != NULL) {
845 _stack_trace->oops_do(f);
846 }
847 if (_concurrent_locks != NULL) {
848 _concurrent_locks->oops_do(f);
849 }
850 }
852 void ThreadSnapshot::metadata_do(void f(Metadata*)) {
853 if (_stack_trace != NULL) {
854 _stack_trace->metadata_do(f);
855 }
856 }
859 DeadlockCycle::DeadlockCycle() {
860 _is_deadlock = false;
861 _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true);
862 _next = NULL;
863 }
865 DeadlockCycle::~DeadlockCycle() {
866 delete _threads;
867 }
869 void DeadlockCycle::print_on(outputStream* st) const {
870 st->cr();
871 st->print_cr("Found one Java-level deadlock:");
872 st->print("=============================");
874 JavaThread* currentThread;
875 ObjectMonitor* waitingToLockMonitor;
876 oop waitingToLockBlocker;
877 int len = _threads->length();
878 for (int i = 0; i < len; i++) {
879 currentThread = _threads->at(i);
880 waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
881 waitingToLockBlocker = currentThread->current_park_blocker();
882 st->cr();
883 st->print_cr("\"%s\":", currentThread->get_thread_name());
884 const char* owner_desc = ",\n which is held by";
885 if (waitingToLockMonitor != NULL) {
886 st->print(" waiting to lock monitor " INTPTR_FORMAT, waitingToLockMonitor);
887 oop obj = (oop)waitingToLockMonitor->object();
888 if (obj != NULL) {
889 st->print(" (object "INTPTR_FORMAT ", a %s)", (address)obj,
890 (InstanceKlass::cast(obj->klass()))->external_name());
892 if (!currentThread->current_pending_monitor_is_from_java()) {
893 owner_desc = "\n in JNI, which is held by";
894 }
895 } else {
896 // No Java object associated - a JVMTI raw monitor
897 owner_desc = " (JVMTI raw monitor),\n which is held by";
898 }
899 currentThread = Threads::owning_thread_from_monitor_owner(
900 (address)waitingToLockMonitor->owner(),
901 false /* no locking needed */);
902 if (currentThread == NULL) {
903 // The deadlock was detected at a safepoint so the JavaThread
904 // that owns waitingToLockMonitor should be findable, but
905 // if it is not findable, then the previous currentThread is
906 // blocked permanently.
907 st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc,
908 (address)waitingToLockMonitor->owner());
909 continue;
910 }
911 } else {
912 st->print(" waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
913 (address)waitingToLockBlocker,
914 (InstanceKlass::cast(waitingToLockBlocker->klass()))->external_name());
915 assert(waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass()),
916 "Must be an AbstractOwnableSynchronizer");
917 oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
918 currentThread = java_lang_Thread::thread(ownerObj);
919 }
920 st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name());
921 }
923 st->cr();
924 st->cr();
926 // Print stack traces
927 bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace;
928 JavaMonitorsInStackTrace = true;
929 st->print_cr("Java stack information for the threads listed above:");
930 st->print_cr("===================================================");
931 for (int j = 0; j < len; j++) {
932 currentThread = _threads->at(j);
933 st->print_cr("\"%s\":", currentThread->get_thread_name());
934 currentThread->print_stack_on(st);
935 }
936 JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace;
937 }
939 ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread,
940 bool include_jvmti_agent_threads,
941 bool include_jni_attaching_threads) {
942 assert(cur_thread == Thread::current(), "Check current thread");
944 int init_size = ThreadService::get_live_thread_count();
945 _threads_array = new GrowableArray<instanceHandle>(init_size);
947 MutexLockerEx ml(Threads_lock);
949 for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
950 // skips JavaThreads in the process of exiting
951 // and also skips VM internal JavaThreads
952 // Threads in _thread_new or _thread_new_trans state are included.
953 // i.e. threads have been started but not yet running.
954 if (jt->threadObj() == NULL ||
955 jt->is_exiting() ||
956 !java_lang_Thread::is_alive(jt->threadObj()) ||
957 jt->is_hidden_from_external_view()) {
958 continue;
959 }
961 // skip agent threads
962 if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) {
963 continue;
964 }
966 // skip jni threads in the process of attaching
967 if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) {
968 continue;
969 }
971 instanceHandle h(cur_thread, (instanceOop) jt->threadObj());
972 _threads_array->append(h);
973 }
974 }