src/share/vm/services/threadService.cpp

Tue, 23 Nov 2010 13:22:55 -0800

author
stefank
date
Tue, 23 Nov 2010 13:22:55 -0800
changeset 2314
f95d63e2154a
parent 1907
c18cbe5936b8
child 2423
b1a2afa37ec4
permissions
-rw-r--r--

6989984: Use standard include model for Hospot
Summary: Replaced MakeDeps and the includeDB files with more standardized solutions.
Reviewed-by: coleenp, kvn, kamg

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

mercurial