src/share/vm/services/threadService.cpp

Mon, 17 Jun 2013 18:35:44 +0200

author
sla
date
Mon, 17 Jun 2013 18:35:44 +0200
changeset 5271
ef748153ee8f
parent 4673
5ee250974db9
child 6122
0b9ea9a72436
permissions
-rw-r--r--

8016304: ThreadMXBean.getDeadlockedThreads reports bogus deadlocks on JDK 8
Reviewed-by: dcubed, mgronlun

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

mercurial