threadService.cpp revision 3465:d2a62e0f25eb
1/*
2 * Copyright (c) 2003, 2011, 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/vmThread.hpp"
37#include "runtime/vm_operations.hpp"
38#include "services/threadService.hpp"
39
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)
45
46// Default is disabled.
47bool ThreadService::_thread_monitoring_contention_enabled = false;
48bool ThreadService::_thread_cpu_time_enabled = false;
49bool ThreadService::_thread_allocated_memory_enabled = false;
50
51PerfCounter*  ThreadService::_total_threads_count = NULL;
52PerfVariable* ThreadService::_live_threads_count = NULL;
53PerfVariable* ThreadService::_peak_threads_count = NULL;
54PerfVariable* ThreadService::_daemon_threads_count = NULL;
55volatile int ThreadService::_exiting_threads_count = 0;
56volatile int ThreadService::_exiting_daemon_threads_count = 0;
57
58ThreadDumpResult* ThreadService::_threaddump_list = NULL;
59
60static const int INITIAL_ARRAY_SIZE = 10;
61
62void ThreadService::init() {
63  EXCEPTION_MARK;
64
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.
68
69  _total_threads_count =
70                PerfDataManager::create_counter(JAVA_THREADS, "started",
71                                                PerfData::U_Events, CHECK);
72
73  _live_threads_count =
74                PerfDataManager::create_variable(JAVA_THREADS, "live",
75                                                 PerfData::U_None, CHECK);
76
77  _peak_threads_count =
78                PerfDataManager::create_variable(JAVA_THREADS, "livePeak",
79                                                 PerfData::U_None, CHECK);
80
81  _daemon_threads_count =
82                PerfDataManager::create_variable(JAVA_THREADS, "daemon",
83                                                 PerfData::U_None, CHECK);
84
85  if (os::is_thread_cpu_time_supported()) {
86    _thread_cpu_time_enabled = true;
87  }
88
89  _thread_allocated_memory_enabled = true; // Always on, so enable it
90}
91
92void 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}
98
99void 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  }
105
106  _total_threads_count->inc();
107  _live_threads_count->inc();
108
109  if (_live_threads_count->get_value() > _peak_threads_count->get_value()) {
110    _peak_threads_count->set_value(_live_threads_count->get_value());
111  }
112
113  if (daemon) {
114    _daemon_threads_count->inc();
115  }
116}
117
118void ThreadService::remove_thread(JavaThread* thread, bool daemon) {
119  Atomic::dec((jint*) &_exiting_threads_count);
120
121  if (thread->is_hidden_from_external_view() ||
122      thread->is_jvmti_agent_thread()) {
123    return;
124  }
125
126  _live_threads_count->set_value(_live_threads_count->get_value() - 1);
127
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}
133
134void ThreadService::current_thread_exiting(JavaThread* jt) {
135  assert(jt == JavaThread::current(), "Called by current thread");
136  Atomic::inc((jint*) &_exiting_threads_count);
137
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}
143
144// FIXME: JVMTI should call this function
145Handle 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");
148
149  ObjectMonitor *wait_obj = thread->current_waiting_monitor();
150
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  }
164
165  Handle h(obj);
166  return h;
167}
168
169bool ThreadService::set_thread_monitoring_contention(bool flag) {
170  MutexLocker m(Management_lock);
171
172  bool prev = _thread_monitoring_contention_enabled;
173  _thread_monitoring_contention_enabled = flag;
174
175  return prev;
176}
177
178bool ThreadService::set_thread_cpu_time_enabled(bool flag) {
179  MutexLocker m(Management_lock);
180
181  bool prev = _thread_cpu_time_enabled;
182  _thread_cpu_time_enabled = flag;
183
184  return prev;
185}
186
187bool ThreadService::set_thread_allocated_memory_enabled(bool flag) {
188  MutexLocker m(Management_lock);
189
190  bool prev = _thread_allocated_memory_enabled;
191  _thread_allocated_memory_enabled = flag;
192
193  return prev;
194}
195
196// GC support
197void ThreadService::oops_do(OopClosure* f) {
198  for (ThreadDumpResult* dump = _threaddump_list; dump != NULL; dump = dump->next()) {
199    dump->oops_do(f);
200  }
201}
202
203void 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}
212
213void ThreadService::remove_thread_dump(ThreadDumpResult* dump) {
214  MutexLocker ml(Management_lock);
215
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}
231
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
235Handle ThreadService::dump_stack_traces(GrowableArray<instanceHandle>* threads,
236                                        int num_threads,
237                                        TRAPS) {
238  assert(num_threads > 0, "just checking");
239
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);
248
249  // Allocate the resulting StackTraceElement[][] object
250
251  ResourceMark rm(THREAD);
252  klassOop k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_StackTraceElement_array(), true, CHECK_NH);
253  objArrayKlassHandle ik (THREAD, k);
254  objArrayOop r = oopFactory::new_objArray(ik(), num_threads, CHECK_NH);
255  objArrayHandle result_obj(THREAD, r);
256
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  }
271
272  return result_obj;
273}
274
275void 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}
281
282void 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}
288
289// Find deadlocks involving object monitors and concurrent locks if concurrent_locks is true
290DeadlockCycle* 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;
298
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  }
303
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    }
312
313    thisDfn = globalDfn;
314    jt->set_depth_first_number(globalDfn++);
315    previousThread = jt;
316    currentThread = jt;
317
318    cycle->reset();
319
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((address)waitingToLockMonitor->owner(),
331                                                                  false /* no locking needed */);
332      } else {
333        if (concurrent_locks) {
334          if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
335            oop threadObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
336            currentThread = threadObj != NULL ? java_lang_Thread::thread(threadObj) : NULL;
337          } else {
338            currentThread = NULL;
339          }
340        }
341      }
342
343      if (currentThread == NULL) {
344        // No dependency on another thread
345        break;
346      }
347      if (currentThread->depth_first_number() < 0) {
348        // First visit to this thread
349        currentThread->set_depth_first_number(globalDfn++);
350      } else if (currentThread->depth_first_number() < thisDfn) {
351        // Thread already visited, and not on a (new) cycle
352        break;
353      } else if (currentThread == previousThread) {
354        // Self-loop, ignore
355        break;
356      } else {
357        // We have a (new) cycle
358        num_deadlocks++;
359
360        cycle->set_deadlock(true);
361
362        // add this cycle to the deadlocks list
363        if (deadlocks == NULL) {
364          deadlocks = cycle;
365        } else {
366          last->set_next(cycle);
367        }
368        last = cycle;
369        cycle = new DeadlockCycle();
370        break;
371      }
372      previousThread = currentThread;
373      waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
374      if (concurrent_locks) {
375        waitingToLockBlocker = currentThread->current_park_blocker();
376      }
377    }
378
379  }
380  delete cycle;
381  return deadlocks;
382}
383
384ThreadDumpResult::ThreadDumpResult() : _num_threads(0), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
385
386  // Create a new ThreadDumpResult object and append to the list.
387  // If GC happens before this function returns, methodOop
388  // in the stack trace will be visited.
389  ThreadService::add_thread_dump(this);
390}
391
392ThreadDumpResult::ThreadDumpResult(int num_threads) : _num_threads(num_threads), _num_snapshots(0), _snapshots(NULL), _next(NULL), _last(NULL) {
393  // Create a new ThreadDumpResult object and append to the list.
394  // If GC happens before this function returns, oops
395  // will be visited.
396  ThreadService::add_thread_dump(this);
397}
398
399ThreadDumpResult::~ThreadDumpResult() {
400  ThreadService::remove_thread_dump(this);
401
402  // free all the ThreadSnapshot objects created during
403  // the VM_ThreadDump operation
404  ThreadSnapshot* ts = _snapshots;
405  while (ts != NULL) {
406    ThreadSnapshot* p = ts;
407    ts = ts->next();
408    delete p;
409  }
410}
411
412
413void ThreadDumpResult::add_thread_snapshot(ThreadSnapshot* ts) {
414  assert(_num_threads == 0 || _num_snapshots < _num_threads,
415         "_num_snapshots must be less than _num_threads");
416  _num_snapshots++;
417  if (_snapshots == NULL) {
418    _snapshots = ts;
419  } else {
420    _last->set_next(ts);
421  }
422  _last = ts;
423}
424
425void ThreadDumpResult::oops_do(OopClosure* f) {
426  for (ThreadSnapshot* ts = _snapshots; ts != NULL; ts = ts->next()) {
427    ts->oops_do(f);
428  }
429}
430
431StackFrameInfo::StackFrameInfo(javaVFrame* jvf, bool with_lock_info) {
432  _method = jvf->method();
433  _bci = jvf->bci();
434  _locked_monitors = NULL;
435  if (with_lock_info) {
436    ResourceMark rm;
437    GrowableArray<MonitorInfo*>* list = jvf->locked_monitors();
438    int length = list->length();
439    if (length > 0) {
440      _locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(length, true);
441      for (int i = 0; i < length; i++) {
442        MonitorInfo* monitor = list->at(i);
443        assert(monitor->owner(), "This monitor must have an owning object");
444        _locked_monitors->append(monitor->owner());
445      }
446    }
447  }
448}
449
450void StackFrameInfo::oops_do(OopClosure* f) {
451  f->do_oop((oop*) &_method);
452  if (_locked_monitors != NULL) {
453    int length = _locked_monitors->length();
454    for (int i = 0; i < length; i++) {
455      f->do_oop((oop*) _locked_monitors->adr_at(i));
456    }
457  }
458}
459
460void StackFrameInfo::print_on(outputStream* st) const {
461  ResourceMark rm;
462  java_lang_Throwable::print_stack_element(st, method(), bci());
463  int len = (_locked_monitors != NULL ? _locked_monitors->length() : 0);
464  for (int i = 0; i < len; i++) {
465    oop o = _locked_monitors->at(i);
466    instanceKlass* ik = instanceKlass::cast(o->klass());
467    st->print_cr("\t- locked <" INTPTR_FORMAT "> (a %s)", (address)o, ik->external_name());
468  }
469
470}
471
472// Iterate through monitor cache to find JNI locked monitors
473class InflatedMonitorsClosure: public MonitorClosure {
474private:
475  ThreadStackTrace* _stack_trace;
476  Thread* _thread;
477public:
478  InflatedMonitorsClosure(Thread* t, ThreadStackTrace* st) {
479    _thread = t;
480    _stack_trace = st;
481  }
482  void do_monitor(ObjectMonitor* mid) {
483    if (mid->owner() == _thread) {
484      oop object = (oop) mid->object();
485      if (!_stack_trace->is_owned_monitor_on_stack(object)) {
486        _stack_trace->add_jni_locked_monitor(object);
487      }
488    }
489  }
490};
491
492ThreadStackTrace::ThreadStackTrace(JavaThread* t, bool with_locked_monitors) {
493  _thread = t;
494  _frames = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<StackFrameInfo*>(INITIAL_ARRAY_SIZE, true);
495  _depth = 0;
496  _with_locked_monitors = with_locked_monitors;
497  if (_with_locked_monitors) {
498    _jni_locked_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<oop>(INITIAL_ARRAY_SIZE, true);
499  } else {
500    _jni_locked_monitors = NULL;
501  }
502}
503
504ThreadStackTrace::~ThreadStackTrace() {
505  for (int i = 0; i < _frames->length(); i++) {
506    delete _frames->at(i);
507  }
508  delete _frames;
509  if (_jni_locked_monitors != NULL) {
510    delete _jni_locked_monitors;
511  }
512}
513
514void ThreadStackTrace::dump_stack_at_safepoint(int maxDepth) {
515  assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
516
517  if (_thread->has_last_Java_frame()) {
518    RegisterMap reg_map(_thread);
519    vframe* start_vf = _thread->last_java_vframe(&reg_map);
520    int count = 0;
521    for (vframe* f = start_vf; f; f = f->sender() ) {
522      if (f->is_java_frame()) {
523        javaVFrame* jvf = javaVFrame::cast(f);
524        add_stack_frame(jvf);
525        count++;
526      } else {
527        // Ignore non-Java frames
528      }
529      if (maxDepth > 0 && count == maxDepth) {
530        // Skip frames if more than maxDepth
531        break;
532      }
533    }
534  }
535
536  if (_with_locked_monitors) {
537    // Iterate inflated monitors and find monitors locked by this thread
538    // not found in the stack
539    InflatedMonitorsClosure imc(_thread, this);
540    ObjectSynchronizer::monitors_iterate(&imc);
541  }
542}
543
544
545bool ThreadStackTrace::is_owned_monitor_on_stack(oop object) {
546  assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
547
548  bool found = false;
549  int num_frames = get_stack_depth();
550  for (int depth = 0; depth < num_frames; depth++) {
551    StackFrameInfo* frame = stack_frame_at(depth);
552    int len = frame->num_locked_monitors();
553    GrowableArray<oop>* locked_monitors = frame->locked_monitors();
554    for (int j = 0; j < len; j++) {
555      oop monitor = locked_monitors->at(j);
556      assert(monitor != NULL && monitor->is_instance(), "must be a Java object");
557      if (monitor == object) {
558        found = true;
559        break;
560      }
561    }
562  }
563  return found;
564}
565
566Handle ThreadStackTrace::allocate_fill_stack_trace_element_array(TRAPS) {
567  klassOop k = SystemDictionary::StackTraceElement_klass();
568  assert(k != NULL, "must be loaded in 1.4+");
569  instanceKlassHandle ik(THREAD, k);
570
571  // Allocate an array of java/lang/StackTraceElement object
572  objArrayOop ste = oopFactory::new_objArray(ik(), _depth, CHECK_NH);
573  objArrayHandle backtrace(THREAD, ste);
574  for (int j = 0; j < _depth; j++) {
575    StackFrameInfo* frame = _frames->at(j);
576    methodHandle mh(THREAD, frame->method());
577    oop element = java_lang_StackTraceElement::create(mh, frame->bci(), CHECK_NH);
578    backtrace->obj_at_put(j, element);
579  }
580  return backtrace;
581}
582
583void ThreadStackTrace::add_stack_frame(javaVFrame* jvf) {
584  StackFrameInfo* frame = new StackFrameInfo(jvf, _with_locked_monitors);
585  _frames->append(frame);
586  _depth++;
587}
588
589void ThreadStackTrace::oops_do(OopClosure* f) {
590  int length = _frames->length();
591  for (int i = 0; i < length; i++) {
592    _frames->at(i)->oops_do(f);
593  }
594
595  length = (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0);
596  for (int j = 0; j < length; j++) {
597    f->do_oop((oop*) _jni_locked_monitors->adr_at(j));
598  }
599}
600
601ConcurrentLocksDump::~ConcurrentLocksDump() {
602  if (_retain_map_on_free) {
603    return;
604  }
605
606  for (ThreadConcurrentLocks* t = _map; t != NULL;)  {
607    ThreadConcurrentLocks* tcl = t;
608    t = t->next();
609    delete tcl;
610  }
611}
612
613void ConcurrentLocksDump::dump_at_safepoint() {
614  // dump all locked concurrent locks
615  assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
616
617  if (JDK_Version::is_gte_jdk16x_version()) {
618    ResourceMark rm;
619
620    GrowableArray<oop>* aos_objects = new GrowableArray<oop>(INITIAL_ARRAY_SIZE);
621
622    // Find all instances of AbstractOwnableSynchronizer
623    HeapInspection::find_instances_at_safepoint(SystemDictionary::abstract_ownable_synchronizer_klass(),
624                                                aos_objects);
625    // Build a map of thread to its owned AQS locks
626    build_map(aos_objects);
627  }
628}
629
630
631// build a map of JavaThread to all its owned AbstractOwnableSynchronizer
632void ConcurrentLocksDump::build_map(GrowableArray<oop>* aos_objects) {
633  int length = aos_objects->length();
634  for (int i = 0; i < length; i++) {
635    oop o = aos_objects->at(i);
636    oop owner_thread_obj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(o);
637    if (owner_thread_obj != NULL) {
638      JavaThread* thread = java_lang_Thread::thread(owner_thread_obj);
639      assert(o->is_instance(), "Must be an instanceOop");
640      add_lock(thread, (instanceOop) o);
641    }
642  }
643}
644
645void ConcurrentLocksDump::add_lock(JavaThread* thread, instanceOop o) {
646  ThreadConcurrentLocks* tcl = thread_concurrent_locks(thread);
647  if (tcl != NULL) {
648    tcl->add_lock(o);
649    return;
650  }
651
652  // First owned lock found for this thread
653  tcl = new ThreadConcurrentLocks(thread);
654  tcl->add_lock(o);
655  if (_map == NULL) {
656    _map = tcl;
657  } else {
658    _last->set_next(tcl);
659  }
660  _last = tcl;
661}
662
663ThreadConcurrentLocks* ConcurrentLocksDump::thread_concurrent_locks(JavaThread* thread) {
664  for (ThreadConcurrentLocks* tcl = _map; tcl != NULL; tcl = tcl->next()) {
665    if (tcl->java_thread() == thread) {
666      return tcl;
667    }
668  }
669  return NULL;
670}
671
672void ConcurrentLocksDump::print_locks_on(JavaThread* t, outputStream* st) {
673  st->print_cr("   Locked ownable synchronizers:");
674  ThreadConcurrentLocks* tcl = thread_concurrent_locks(t);
675  GrowableArray<instanceOop>* locks = (tcl != NULL ? tcl->owned_locks() : NULL);
676  if (locks == NULL || locks->is_empty()) {
677    st->print_cr("\t- None");
678    st->cr();
679    return;
680  }
681
682  for (int i = 0; i < locks->length(); i++) {
683    instanceOop obj = locks->at(i);
684    instanceKlass* ik = instanceKlass::cast(obj->klass());
685    st->print_cr("\t- <" INTPTR_FORMAT "> (a %s)", (address)obj, ik->external_name());
686  }
687  st->cr();
688}
689
690ThreadConcurrentLocks::ThreadConcurrentLocks(JavaThread* thread) {
691  _thread = thread;
692  _owned_locks = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<instanceOop>(INITIAL_ARRAY_SIZE, true);
693  _next = NULL;
694}
695
696ThreadConcurrentLocks::~ThreadConcurrentLocks() {
697  delete _owned_locks;
698}
699
700void ThreadConcurrentLocks::add_lock(instanceOop o) {
701  _owned_locks->append(o);
702}
703
704void ThreadConcurrentLocks::oops_do(OopClosure* f) {
705  int length = _owned_locks->length();
706  for (int i = 0; i < length; i++) {
707    f->do_oop((oop*) _owned_locks->adr_at(i));
708  }
709}
710
711ThreadStatistics::ThreadStatistics() {
712  _contended_enter_count = 0;
713  _monitor_wait_count = 0;
714  _sleep_count = 0;
715  _count_pending_reset = false;
716  _timer_pending_reset = false;
717  memset((void*) _perf_recursion_counts, 0, sizeof(_perf_recursion_counts));
718}
719
720ThreadSnapshot::ThreadSnapshot(JavaThread* thread) {
721  _thread = thread;
722  _threadObj = thread->threadObj();
723  _stack_trace = NULL;
724  _concurrent_locks = NULL;
725  _next = NULL;
726
727  ThreadStatistics* stat = thread->get_thread_stat();
728  _contended_enter_ticks = stat->contended_enter_ticks();
729  _contended_enter_count = stat->contended_enter_count();
730  _monitor_wait_ticks = stat->monitor_wait_ticks();
731  _monitor_wait_count = stat->monitor_wait_count();
732  _sleep_ticks = stat->sleep_ticks();
733  _sleep_count = stat->sleep_count();
734
735  _blocker_object = NULL;
736  _blocker_object_owner = NULL;
737
738  _thread_status = java_lang_Thread::get_thread_status(_threadObj);
739  _is_ext_suspended = thread->is_being_ext_suspended();
740  _is_in_native = (thread->thread_state() == _thread_in_native);
741
742  if (_thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER ||
743      _thread_status == java_lang_Thread::IN_OBJECT_WAIT ||
744      _thread_status == java_lang_Thread::IN_OBJECT_WAIT_TIMED) {
745
746    Handle obj = ThreadService::get_current_contended_monitor(thread);
747    if (obj() == NULL) {
748      // monitor no longer exists; thread is not blocked
749      _thread_status = java_lang_Thread::RUNNABLE;
750    } else {
751      _blocker_object = obj();
752      JavaThread* owner = ObjectSynchronizer::get_lock_owner(obj, false);
753      if ((owner == NULL && _thread_status == java_lang_Thread::BLOCKED_ON_MONITOR_ENTER)
754          || (owner != NULL && owner->is_attaching_via_jni())) {
755        // ownership information of the monitor is not available
756        // (may no longer be owned or releasing to some other thread)
757        // make this thread in RUNNABLE state.
758        // And when the owner thread is in attaching state, the java thread
759        // is not completely initialized. For example thread name and id
760        // and may not be set, so hide the attaching thread.
761        _thread_status = java_lang_Thread::RUNNABLE;
762        _blocker_object = NULL;
763      } else if (owner != NULL) {
764        _blocker_object_owner = owner->threadObj();
765      }
766    }
767  }
768
769  // Support for JSR-166 locks
770  if (JDK_Version::current().supports_thread_park_blocker() &&
771        (_thread_status == java_lang_Thread::PARKED ||
772         _thread_status == java_lang_Thread::PARKED_TIMED)) {
773
774    _blocker_object = thread->current_park_blocker();
775    if (_blocker_object != NULL && _blocker_object->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
776      _blocker_object_owner = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(_blocker_object);
777    }
778  }
779}
780
781ThreadSnapshot::~ThreadSnapshot() {
782  delete _stack_trace;
783  delete _concurrent_locks;
784}
785
786void ThreadSnapshot::dump_stack_at_safepoint(int max_depth, bool with_locked_monitors) {
787  _stack_trace = new ThreadStackTrace(_thread, with_locked_monitors);
788  _stack_trace->dump_stack_at_safepoint(max_depth);
789}
790
791
792void ThreadSnapshot::oops_do(OopClosure* f) {
793  f->do_oop(&_threadObj);
794  f->do_oop(&_blocker_object);
795  f->do_oop(&_blocker_object_owner);
796  if (_stack_trace != NULL) {
797    _stack_trace->oops_do(f);
798  }
799  if (_concurrent_locks != NULL) {
800    _concurrent_locks->oops_do(f);
801  }
802}
803
804DeadlockCycle::DeadlockCycle() {
805  _is_deadlock = false;
806  _threads = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JavaThread*>(INITIAL_ARRAY_SIZE, true);
807  _next = NULL;
808}
809
810DeadlockCycle::~DeadlockCycle() {
811  delete _threads;
812}
813
814void DeadlockCycle::print_on(outputStream* st) const {
815  st->cr();
816  st->print_cr("Found one Java-level deadlock:");
817  st->print("=============================");
818
819  JavaThread* currentThread;
820  ObjectMonitor* waitingToLockMonitor;
821  oop waitingToLockBlocker;
822  int len = _threads->length();
823  for (int i = 0; i < len; i++) {
824    currentThread = _threads->at(i);
825    waitingToLockMonitor = (ObjectMonitor*)currentThread->current_pending_monitor();
826    waitingToLockBlocker = currentThread->current_park_blocker();
827    st->cr();
828    st->print_cr("\"%s\":", currentThread->get_thread_name());
829    const char* owner_desc = ",\n  which is held by";
830    if (waitingToLockMonitor != NULL) {
831      st->print("  waiting to lock monitor " INTPTR_FORMAT, waitingToLockMonitor);
832      oop obj = (oop)waitingToLockMonitor->object();
833      if (obj != NULL) {
834        st->print(" (object "INTPTR_FORMAT ", a %s)", (address)obj,
835                   (instanceKlass::cast(obj->klass()))->external_name());
836
837        if (!currentThread->current_pending_monitor_is_from_java()) {
838          owner_desc = "\n  in JNI, which is held by";
839        }
840      } else {
841        // No Java object associated - a JVMTI raw monitor
842        owner_desc = " (JVMTI raw monitor),\n  which is held by";
843      }
844      currentThread = Threads::owning_thread_from_monitor_owner(
845        (address)waitingToLockMonitor->owner(), false /* no locking needed */);
846    } else {
847      st->print("  waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
848                (address)waitingToLockBlocker,
849                (instanceKlass::cast(waitingToLockBlocker->klass()))->external_name());
850      assert(waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass()),
851             "Must be an AbstractOwnableSynchronizer");
852      oop ownerObj = java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(waitingToLockBlocker);
853      currentThread = java_lang_Thread::thread(ownerObj);
854    }
855    st->print("%s \"%s\"", owner_desc, currentThread->get_thread_name());
856  }
857
858  st->cr();
859  st->cr();
860
861  // Print stack traces
862  bool oldJavaMonitorsInStackTrace = JavaMonitorsInStackTrace;
863  JavaMonitorsInStackTrace = true;
864  st->print_cr("Java stack information for the threads listed above:");
865  st->print_cr("===================================================");
866  for (int j = 0; j < len; j++) {
867    currentThread = _threads->at(j);
868    st->print_cr("\"%s\":", currentThread->get_thread_name());
869    currentThread->print_stack_on(st);
870  }
871  JavaMonitorsInStackTrace = oldJavaMonitorsInStackTrace;
872}
873
874ThreadsListEnumerator::ThreadsListEnumerator(Thread* cur_thread,
875                                             bool include_jvmti_agent_threads,
876                                             bool include_jni_attaching_threads) {
877  assert(cur_thread == Thread::current(), "Check current thread");
878
879  int init_size = ThreadService::get_live_thread_count();
880  _threads_array = new GrowableArray<instanceHandle>(init_size);
881
882  MutexLockerEx ml(Threads_lock);
883
884  for (JavaThread* jt = Threads::first(); jt != NULL; jt = jt->next()) {
885    // skips JavaThreads in the process of exiting
886    // and also skips VM internal JavaThreads
887    // Threads in _thread_new or _thread_new_trans state are included.
888    // i.e. threads have been started but not yet running.
889    if (jt->threadObj() == NULL   ||
890        jt->is_exiting() ||
891        !java_lang_Thread::is_alive(jt->threadObj())   ||
892        jt->is_hidden_from_external_view()) {
893      continue;
894    }
895
896    // skip agent threads
897    if (!include_jvmti_agent_threads && jt->is_jvmti_agent_thread()) {
898      continue;
899    }
900
901    // skip jni threads in the process of attaching
902    if (!include_jni_attaching_threads && jt->is_attaching_via_jni()) {
903      continue;
904    }
905
906    instanceHandle h(cur_thread, (instanceOop) jt->threadObj());
907    _threads_array->append(h);
908  }
909}
910