threadService.hpp 21.1 KB
Newer Older
D
duke 已提交
1
/*
X
xdono 已提交
2
 * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 *
 */

class OopClosure;
class ThreadDumpResult;
class ThreadStackTrace;
class ThreadSnapshot;
class StackFrameInfo;
class ThreadConcurrentLocks;
class DeadlockCycle;

// VM monitoring and management support for the thread and
// synchronization subsystem
//
// Thread contention monitoring is disabled by default.
// When enabled, the VM will begin measuring the accumulated
// elapsed time a thread blocked on synchronization.
//
class ThreadService : public AllStatic {
private:
  // These counters could be moved to Threads class
  static PerfCounter*  _total_threads_count;
  static PerfVariable* _live_threads_count;
  static PerfVariable* _peak_threads_count;
  static PerfVariable* _daemon_threads_count;

  // These 2 counters are atomically incremented once the thread is exiting.
  // They will be atomically decremented when ThreadService::remove_thread is called.
  static volatile int  _exiting_threads_count;
  static volatile int  _exiting_daemon_threads_count;

  static bool          _thread_monitoring_contention_enabled;
  static bool          _thread_cpu_time_enabled;

  // Need to keep the list of thread dump result that
  // keep references to methodOop since thread dump can be
  // requested by multiple threads concurrently.
  static ThreadDumpResult* _threaddump_list;

public:
  static void init();
  static void add_thread(JavaThread* thread, bool daemon);
  static void remove_thread(JavaThread* thread, bool daemon);
  static void current_thread_exiting(JavaThread* jt);

  static bool set_thread_monitoring_contention(bool flag);
  static bool is_thread_monitoring_contention() { return _thread_monitoring_contention_enabled; }

  static bool set_thread_cpu_time_enabled(bool flag);
  static bool is_thread_cpu_time_enabled()    { return _thread_cpu_time_enabled; }

  static jlong get_total_thread_count()       { return _total_threads_count->get_value(); }
  static jlong get_peak_thread_count()        { return _peak_threads_count->get_value(); }
  static jlong get_live_thread_count()        { return _live_threads_count->get_value() - _exiting_threads_count; }
  static jlong get_daemon_thread_count()      { return _daemon_threads_count->get_value() - _exiting_daemon_threads_count; }

  static int   exiting_threads_count()        { return _exiting_threads_count; }
  static int   exiting_daemon_threads_count() { return _exiting_daemon_threads_count; }

  // Support for thread dump
  static void   add_thread_dump(ThreadDumpResult* dump);
  static void   remove_thread_dump(ThreadDumpResult* dump);

  static Handle get_current_contended_monitor(JavaThread* thread);

  // This function is called by JVM_DumpThreads.
  static Handle dump_stack_traces(GrowableArray<instanceHandle>* threads,
                                  int num_threads, TRAPS);

  static void   reset_peak_thread_count();
  static void   reset_contention_count_stat(JavaThread* thread);
  static void   reset_contention_time_stat(JavaThread* thread);

  static DeadlockCycle*       find_deadlocks_at_safepoint(bool object_monitors_only);

  // GC support
  static void   oops_do(OopClosure* f);
};

// Per-thread Statistics for synchronization
class ThreadStatistics : public CHeapObj {
private:
  // The following contention statistics are only updated by
  // the thread owning these statistics when contention occurs.

  jlong        _contended_enter_count;
  elapsedTimer _contended_enter_timer;
  jlong        _monitor_wait_count;
  elapsedTimer _monitor_wait_timer;
  jlong        _sleep_count;
  elapsedTimer _sleep_timer;


  // These two reset flags are set to true when another thread
  // requests to reset the statistics.  The actual statistics
  // are reset when the thread contention occurs and attempts
  // to update the statistics.
  bool         _count_pending_reset;
  bool         _timer_pending_reset;

  // Keep accurate times for potentially recursive class operations
  int          _class_init_recursion_count;
  int          _class_verify_recursion_count;
  int          _class_link_recursion_count;

  // utility functions
  void  check_and_reset_count()            {
                                             if (!_count_pending_reset) return;
                                             _contended_enter_count = 0;
                                             _monitor_wait_count = 0;
                                             _sleep_count = 0;
                                             _count_pending_reset = 0;
                                           }
  void  check_and_reset_timer()            {
                                             if (!_timer_pending_reset) return;
                                             _contended_enter_timer.reset();
                                             _monitor_wait_timer.reset();
                                             _sleep_timer.reset();
                                             _timer_pending_reset = 0;
                                           }

public:
  ThreadStatistics();

  jlong contended_enter_count()            { return (_count_pending_reset ? 0 : _contended_enter_count); }
  jlong contended_enter_ticks()            { return (_timer_pending_reset ? 0 : _contended_enter_timer.active_ticks()); }
  jlong monitor_wait_count()               { return (_count_pending_reset ? 0 : _monitor_wait_count); }
  jlong monitor_wait_ticks()               { return (_timer_pending_reset ? 0 : _monitor_wait_timer.active_ticks()); }
  jlong sleep_count()                      { return (_count_pending_reset ? 0 : _sleep_count); }
  jlong sleep_ticks()                      { return (_timer_pending_reset ? 0 : _sleep_timer.active_ticks()); }

  void monitor_wait()                      { check_and_reset_count(); _monitor_wait_count++; }
  void monitor_wait_begin()                { check_and_reset_timer(); _monitor_wait_timer.start(); }
  void monitor_wait_end()                  { _monitor_wait_timer.stop(); check_and_reset_timer(); }

  void thread_sleep()                      { check_and_reset_count(); _sleep_count++; }
  void thread_sleep_begin()                { check_and_reset_timer(); _sleep_timer.start(); }
  void thread_sleep_end()                  { _sleep_timer.stop(); check_and_reset_timer(); }

  void contended_enter()                   { check_and_reset_count(); _contended_enter_count++; }
  void contended_enter_begin()             { check_and_reset_timer(); _contended_enter_timer.start(); }
  void contended_enter_end()               { _contended_enter_timer.stop(); check_and_reset_timer(); }

  void reset_count_stat()                  { _count_pending_reset = true; }
  void reset_time_stat()                   { _timer_pending_reset = true; }

  int* class_init_recursion_count_addr()   { return &_class_init_recursion_count; }
  int* class_verify_recursion_count_addr() { return &_class_verify_recursion_count; }
  int* class_link_recursion_count_addr()   { return &_class_link_recursion_count; }
};

// Thread snapshot to represent the thread state and statistics
class ThreadSnapshot : public CHeapObj {
private:
  JavaThread* _thread;
  oop         _threadObj;
  java_lang_Thread::ThreadStatus _thread_status;

  bool    _is_ext_suspended;
  bool    _is_in_native;

  jlong   _contended_enter_ticks;
  jlong   _contended_enter_count;
  jlong   _monitor_wait_ticks;
  jlong   _monitor_wait_count;
  jlong   _sleep_ticks;
  jlong   _sleep_count;
  oop     _blocker_object;
  oop     _blocker_object_owner;

  ThreadStackTrace*      _stack_trace;
  ThreadConcurrentLocks* _concurrent_locks;
  ThreadSnapshot*        _next;

public:
  // Dummy snapshot
  ThreadSnapshot() : _thread(NULL), _threadObj(NULL), _stack_trace(NULL), _concurrent_locks(NULL), _next(NULL),
                     _blocker_object(NULL), _blocker_object_owner(NULL) {};
  ThreadSnapshot(JavaThread* thread);
  ~ThreadSnapshot();

  java_lang_Thread::ThreadStatus thread_status() { return _thread_status; }

  oop         threadObj() const           { return _threadObj; }

  void        set_next(ThreadSnapshot* n) { _next = n; }

  bool        is_ext_suspended()          { return _is_ext_suspended; }
  bool        is_in_native()              { return _is_in_native; }

  jlong       contended_enter_count()     { return _contended_enter_count; }
  jlong       contended_enter_ticks()     { return _contended_enter_ticks; }
  jlong       monitor_wait_count()        { return _monitor_wait_count; }
  jlong       monitor_wait_ticks()        { return _monitor_wait_ticks; }
  jlong       sleep_count()               { return _sleep_count; }
  jlong       sleep_ticks()               { return _sleep_ticks; }


  oop         blocker_object()            { return _blocker_object; }
  oop         blocker_object_owner()      { return _blocker_object_owner; }

  ThreadSnapshot*   next() const          { return _next; }
  ThreadStackTrace* get_stack_trace()     { return _stack_trace; }
  ThreadConcurrentLocks* get_concurrent_locks()     { return _concurrent_locks; }

  void        dump_stack_at_safepoint(int max_depth, bool with_locked_monitors);
  void        set_concurrent_locks(ThreadConcurrentLocks* l) { _concurrent_locks = l; }
  void        oops_do(OopClosure* f);
};

class ThreadStackTrace : public CHeapObj {
 private:
  JavaThread*                     _thread;
  int                             _depth;  // number of stack frames added
  bool                            _with_locked_monitors;
  GrowableArray<StackFrameInfo*>* _frames;
  GrowableArray<oop>*             _jni_locked_monitors;

 public:

  ThreadStackTrace(JavaThread* thread, bool with_locked_monitors);
  ~ThreadStackTrace();

245
  JavaThread*     thread()              { return _thread; }
D
duke 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  StackFrameInfo* stack_frame_at(int i) { return _frames->at(i); }
  int             get_stack_depth()     { return _depth; }

  void            add_stack_frame(javaVFrame* jvf);
  void            dump_stack_at_safepoint(int max_depth);
  Handle          allocate_fill_stack_trace_element_array(TRAPS);
  void            oops_do(OopClosure* f);
  GrowableArray<oop>* jni_locked_monitors() { return _jni_locked_monitors; }
  int             num_jni_locked_monitors() { return (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0); }

  bool            is_owned_monitor_on_stack(oop object);
  void            add_jni_locked_monitor(oop object) { _jni_locked_monitors->append(object); }
};

// StackFrameInfo for keeping methodOop and bci during
// stack walking for later construction of StackTraceElement[]
// Java instances
class StackFrameInfo : public CHeapObj {
 private:
  methodOop           _method;
  int                 _bci;
  GrowableArray<oop>* _locked_monitors; // list of object monitors locked by this frame

 public:

  StackFrameInfo(javaVFrame* jvf, bool with_locked_monitors);
  ~StackFrameInfo() {
    if (_locked_monitors != NULL) {
      delete _locked_monitors;
    }
  };
  methodOop method() const       { return _method; }
  int       bci()    const       { return _bci; }
  void      oops_do(OopClosure* f);

  int       num_locked_monitors()       { return (_locked_monitors != NULL ? _locked_monitors->length() : 0); }
  GrowableArray<oop>* locked_monitors() { return _locked_monitors; }

  void      print_on(outputStream* st) const;
};

class ThreadConcurrentLocks : public CHeapObj {
private:
  GrowableArray<instanceOop>* _owned_locks;
  ThreadConcurrentLocks*      _next;
  JavaThread*                 _thread;
 public:
  ThreadConcurrentLocks(JavaThread* thread);
  ~ThreadConcurrentLocks();

  void                        add_lock(instanceOop o);
  void                        set_next(ThreadConcurrentLocks* n) { _next = n; }
  ThreadConcurrentLocks*      next() { return _next; }
  JavaThread*                 java_thread()                      { return _thread; }
  GrowableArray<instanceOop>* owned_locks()                      { return _owned_locks; }
  void                        oops_do(OopClosure* f);
};

class ConcurrentLocksDump : public StackObj {
 private:
  ThreadConcurrentLocks* _map;
  ThreadConcurrentLocks* _last;   // Last ThreadConcurrentLocks in the map
  bool                   _retain_map_on_free;

  void build_map(GrowableArray<oop>* aos_objects);
  void add_lock(JavaThread* thread, instanceOop o);

 public:
  ConcurrentLocksDump(bool retain_map_on_free) : _map(NULL), _last(NULL), _retain_map_on_free(retain_map_on_free) {};
  ConcurrentLocksDump() : _map(NULL), _last(NULL), _retain_map_on_free(false) {};
  ~ConcurrentLocksDump();

  void                        dump_at_safepoint();
  ThreadConcurrentLocks*      thread_concurrent_locks(JavaThread* thread);
  void                        print_locks_on(JavaThread* t, outputStream* st);
};

class ThreadDumpResult : public StackObj {
 private:
  int                  _num_threads;
  int                  _num_snapshots;
  ThreadSnapshot*      _snapshots;
  ThreadSnapshot*      _last;
  ThreadDumpResult*    _next;
 public:
  ThreadDumpResult();
  ThreadDumpResult(int num_threads);
  ~ThreadDumpResult();

  void                 add_thread_snapshot(ThreadSnapshot* ts);
  void                 set_next(ThreadDumpResult* next) { _next = next; }
  ThreadDumpResult*    next()                           { return _next; }
  int                  num_threads()                    { return _num_threads; }
  int                  num_snapshots()                  { return _num_snapshots; }
  ThreadSnapshot*      snapshots()                      { return _snapshots; }
  void                 oops_do(OopClosure* f);
};

class DeadlockCycle : public CHeapObj {
 private:
  bool _is_deadlock;
  GrowableArray<JavaThread*>* _threads;
  DeadlockCycle*              _next;
 public:
  DeadlockCycle();
  ~DeadlockCycle();

  DeadlockCycle* next()                     { return _next; }
  void           set_next(DeadlockCycle* d) { _next = d; }
  void           add_thread(JavaThread* t)  { _threads->append(t); }
  void           reset()                    { _is_deadlock = false; _threads->clear(); }
  void           set_deadlock(bool value)   { _is_deadlock = value; }
  bool           is_deadlock()              { return _is_deadlock; }
  int            num_threads()              { return _threads->length(); }
  GrowableArray<JavaThread*>* threads()     { return _threads; }
  void           print_on(outputStream* st) const;
};

// Utility class to get list of java threads.
class ThreadsListEnumerator : public StackObj {
private:
  GrowableArray<instanceHandle>* _threads_array;
public:
  ThreadsListEnumerator(Thread* cur_thread,
                        bool include_jvmti_agent_threads = false,
                        bool include_jni_attaching_threads = true);
  int            num_threads()            { return _threads_array->length(); }
  instanceHandle get_threadObj(int index) { return _threads_array->at(index); }
};


// abstract utility class to set new thread states, and restore previous after the block exits
class JavaThreadStatusChanger : public StackObj {
 private:
  java_lang_Thread::ThreadStatus _old_state;
  JavaThread*  _java_thread;
  bool _is_alive;

  void save_old_state(JavaThread* java_thread) {
    _java_thread  = java_thread;
    _is_alive = is_alive(java_thread);
    if (is_alive()) {
      _old_state = java_lang_Thread::get_thread_status(_java_thread->threadObj());
    }
  }

 public:
  static void set_thread_status(JavaThread* java_thread,
                                java_lang_Thread::ThreadStatus state) {
    java_lang_Thread::set_thread_status(java_thread->threadObj(), state);
  }

  void set_thread_status(java_lang_Thread::ThreadStatus state) {
    if (is_alive()) {
      set_thread_status(_java_thread, state);
    }
  }

  JavaThreadStatusChanger(JavaThread* java_thread,
                          java_lang_Thread::ThreadStatus state) {
    save_old_state(java_thread);
    set_thread_status(state);
  }

  JavaThreadStatusChanger(JavaThread* java_thread) {
    save_old_state(java_thread);
  }

  ~JavaThreadStatusChanger() {
    set_thread_status(_old_state);
  }

  static bool is_alive(JavaThread* java_thread) {
    return java_thread != NULL && java_thread->threadObj() != NULL;
  }

  bool is_alive() {
    return _is_alive;
  }
};

// Change status to waiting on an object  (timed or indefinite)
class JavaThreadInObjectWaitState : public JavaThreadStatusChanger {
 private:
  ThreadStatistics* _stat;
  bool _active;

 public:
  JavaThreadInObjectWaitState(JavaThread *java_thread, bool timed) :
    JavaThreadStatusChanger(java_thread,
                            timed ? java_lang_Thread::IN_OBJECT_WAIT_TIMED : java_lang_Thread::IN_OBJECT_WAIT) {
    if (is_alive()) {
      _stat = java_thread->get_thread_stat();
      _active = ThreadService::is_thread_monitoring_contention();
      _stat->monitor_wait();
      if (_active) {
        _stat->monitor_wait_begin();
      }
    } else {
      _active = false;
    }
  }

  ~JavaThreadInObjectWaitState() {
    if (_active) {
      _stat->monitor_wait_end();
    }
  }
};

// Change status to parked (timed or indefinite)
class JavaThreadParkedState : public JavaThreadStatusChanger {
 private:
  ThreadStatistics* _stat;
  bool _active;

 public:
  JavaThreadParkedState(JavaThread *java_thread, bool timed) :
    JavaThreadStatusChanger(java_thread,
                            timed ? java_lang_Thread::PARKED_TIMED : java_lang_Thread::PARKED) {
    if (is_alive()) {
      _stat = java_thread->get_thread_stat();
      _active = ThreadService::is_thread_monitoring_contention();
      _stat->monitor_wait();
      if (_active) {
        _stat->monitor_wait_begin();
      }
    } else {
      _active = false;
    }
  }

  ~JavaThreadParkedState() {
    if (_active) {
      _stat->monitor_wait_end();
    }
  }
};

// Change status to blocked on (re-)entering a synchronization block
class JavaThreadBlockedOnMonitorEnterState : public JavaThreadStatusChanger {
 private:
  ThreadStatistics* _stat;
  bool _active;

  static bool contended_enter_begin(JavaThread *java_thread) {
    set_thread_status(java_thread, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
    ThreadStatistics* stat = java_thread->get_thread_stat();
    stat->contended_enter();
    bool active = ThreadService::is_thread_monitoring_contention();
    if (active) {
      stat->contended_enter_begin();
    }
    return active;
  }

 public:
  // java_thread is waiting thread being blocked on monitor reenter.
  // Current thread is the notifying thread which holds the monitor.
  static bool wait_reenter_begin(JavaThread *java_thread, ObjectMonitor *obj_m) {
    assert((java_thread != NULL), "Java thread should not be null here");
    bool active  = false;
    if (is_alive(java_thread) && ServiceUtil::visible_oop((oop)obj_m->object())) {
      active = contended_enter_begin(java_thread);
    }
    return active;
  }

  static void wait_reenter_end(JavaThread *java_thread, bool active) {
    if (active) {
      java_thread->get_thread_stat()->contended_enter_end();
    }
    set_thread_status(java_thread, java_lang_Thread::RUNNABLE);
  }

  JavaThreadBlockedOnMonitorEnterState(JavaThread *java_thread, ObjectMonitor *obj_m) :
    JavaThreadStatusChanger(java_thread) {
    assert((java_thread != NULL), "Java thread should not be null here");
    // Change thread status and collect contended enter stats for monitor contended
    // enter done for external java world objects and it is contended. All other cases
    // like for vm internal objects and for external objects which are not contended
    // thread status is not changed and contended enter stat is not collected.
    _active = false;
    if (is_alive() && ServiceUtil::visible_oop((oop)obj_m->object()) && obj_m->contentions() > 0) {
      _stat = java_thread->get_thread_stat();
      _active = contended_enter_begin(java_thread);
    }
  }

  ~JavaThreadBlockedOnMonitorEnterState() {
    if (_active) {
      _stat->contended_enter_end();
    }
  }
};

// Change status to sleeping
class JavaThreadSleepState : public JavaThreadStatusChanger {
 private:
  ThreadStatistics* _stat;
  bool _active;
 public:
  JavaThreadSleepState(JavaThread *java_thread) :
    JavaThreadStatusChanger(java_thread, java_lang_Thread::SLEEPING) {
    if (is_alive()) {
      _stat = java_thread->get_thread_stat();
      _active = ThreadService::is_thread_monitoring_contention();
      _stat->thread_sleep();
      if (_active) {
        _stat->thread_sleep_begin();
      }
    } else {
      _active = false;
    }
  }

  ~JavaThreadSleepState() {
    if (_active) {
      _stat->thread_sleep_end();
    }
  }
};