1 /*
   2  * Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_SERVICES_THREADSERVICE_HPP
  26 #define SHARE_SERVICES_THREADSERVICE_HPP
  27 
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/javaClasses.hpp"
  30 #include "runtime/handles.hpp"
  31 #include "runtime/init.hpp"
  32 #include "runtime/jniHandles.hpp"
  33 #include "runtime/objectMonitor.hpp"
  34 #include "runtime/perfData.hpp"
  35 #include "runtime/safepoint.hpp"
  36 #include "runtime/thread.hpp"
  37 #include "runtime/threadSMR.hpp"
  38 #include "services/management.hpp"
  39 
  40 class OopClosure;
  41 class ThreadDumpResult;
  42 class ThreadStackTrace;
  43 class ThreadSnapshot;
  44 class StackFrameInfo;
  45 class ThreadConcurrentLocks;
  46 class DeadlockCycle;
  47 
  48 // VM monitoring and management support for the thread and
  49 // synchronization subsystem
  50 //
  51 // Thread contention monitoring is disabled by default.
  52 // When enabled, the VM will begin measuring the accumulated
  53 // elapsed time a thread blocked on synchronization.
  54 //
  55 class ThreadService : public AllStatic {
  56 private:
  57   // These counters could be moved to Threads class
  58   static PerfCounter*  _total_threads_count;
  59   static PerfVariable* _live_threads_count;
  60   static PerfVariable* _peak_threads_count;
  61   static PerfVariable* _daemon_threads_count;
  62 
  63   // These 2 counters are like the above thread counts, but are
  64   // atomically decremented in ThreadService::current_thread_exiting instead of
  65   // ThreadService::remove_thread, so that the thread count is updated before
  66   // Thread.join() returns.
  67   static volatile int  _atomic_threads_count;
  68   static volatile int  _atomic_daemon_threads_count;
  69 
  70   static bool          _thread_monitoring_contention_enabled;
  71   static bool          _thread_cpu_time_enabled;
  72   static bool          _thread_allocated_memory_enabled;
  73 
  74   // Need to keep the list of thread dump result that
  75   // keep references to Method* since thread dump can be
  76   // requested by multiple threads concurrently.
  77   static ThreadDumpResult* _threaddump_list;
  78 
  79   static void decrement_thread_counts(JavaThread* jt, bool daemon);
  80 
  81 public:
  82   static void init();
  83   static void add_thread(JavaThread* thread, bool daemon);
  84   static void remove_thread(JavaThread* thread, bool daemon);
  85   static void current_thread_exiting(JavaThread* jt, bool daemon);
  86 
  87   static bool set_thread_monitoring_contention(bool flag);
  88   static bool is_thread_monitoring_contention() { return _thread_monitoring_contention_enabled; }
  89 
  90   static bool set_thread_cpu_time_enabled(bool flag);
  91   static bool is_thread_cpu_time_enabled()    { return _thread_cpu_time_enabled; }
  92 
  93   static bool set_thread_allocated_memory_enabled(bool flag);
  94   static bool is_thread_allocated_memory_enabled() { return _thread_allocated_memory_enabled; }
  95 
  96   static jlong get_total_thread_count()       { return _total_threads_count->get_value(); }
  97   static jlong get_peak_thread_count()        { return _peak_threads_count->get_value(); }
  98   static jlong get_live_thread_count()        { return _atomic_threads_count; }
  99   static jlong get_daemon_thread_count()      { return _atomic_daemon_threads_count; }
 100 
 101   // Support for thread dump
 102   static void   add_thread_dump(ThreadDumpResult* dump);
 103   static void   remove_thread_dump(ThreadDumpResult* dump);
 104 
 105   static Handle get_current_contended_monitor(JavaThread* thread);
 106 
 107   // This function is called by JVM_DumpThreads.
 108   static Handle dump_stack_traces(GrowableArray<instanceHandle>* threads,
 109                                   int num_threads, TRAPS);
 110 
 111   static void   reset_peak_thread_count();
 112   static void   reset_contention_count_stat(JavaThread* thread);
 113   static void   reset_contention_time_stat(JavaThread* thread);
 114 
 115   static DeadlockCycle*       find_deadlocks_at_safepoint(ThreadsList * t_list, bool object_monitors_only);
 116 
 117   // GC support
 118   static void   oops_do(OopClosure* f);
 119   static void   metadata_do(void f(Metadata*));
 120 };
 121 
 122 // Per-thread Statistics for synchronization
 123 class ThreadStatistics : public CHeapObj<mtInternal> {
 124 private:
 125   // The following contention statistics are only updated by
 126   // the thread owning these statistics when contention occurs.
 127 
 128   jlong        _contended_enter_count;
 129   elapsedTimer _contended_enter_timer;
 130   jlong        _monitor_wait_count;
 131   elapsedTimer _monitor_wait_timer;
 132   jlong        _sleep_count;
 133   elapsedTimer _sleep_timer;
 134 
 135 
 136   // These two reset flags are set to true when another thread
 137   // requests to reset the statistics.  The actual statistics
 138   // are reset when the thread contention occurs and attempts
 139   // to update the statistics.
 140   bool         _count_pending_reset;
 141   bool         _timer_pending_reset;
 142 
 143   // Keep accurate times for potentially recursive class operations
 144   int           _perf_recursion_counts[PerfClassTraceTime::EVENT_TYPE_COUNT];
 145   elapsedTimer  _perf_timers[PerfClassTraceTime::EVENT_TYPE_COUNT];
 146 
 147   // utility functions
 148   void  check_and_reset_count()            {
 149                                              if (!_count_pending_reset) return;
 150                                              _contended_enter_count = 0;
 151                                              _monitor_wait_count = 0;
 152                                              _sleep_count = 0;
 153                                              _count_pending_reset = 0;
 154                                            }
 155   void  check_and_reset_timer()            {
 156                                              if (!_timer_pending_reset) return;
 157                                              _contended_enter_timer.reset();
 158                                              _monitor_wait_timer.reset();
 159                                              _sleep_timer.reset();
 160                                              _timer_pending_reset = 0;
 161                                            }
 162 
 163 public:
 164   ThreadStatistics();
 165 
 166   jlong contended_enter_count()            { return (_count_pending_reset ? 0 : _contended_enter_count); }
 167   jlong contended_enter_ticks()            { return (_timer_pending_reset ? 0 : _contended_enter_timer.active_ticks()); }
 168   jlong monitor_wait_count()               { return (_count_pending_reset ? 0 : _monitor_wait_count); }
 169   jlong monitor_wait_ticks()               { return (_timer_pending_reset ? 0 : _monitor_wait_timer.active_ticks()); }
 170   jlong sleep_count()                      { return (_count_pending_reset ? 0 : _sleep_count); }
 171   jlong sleep_ticks()                      { return (_timer_pending_reset ? 0 : _sleep_timer.active_ticks()); }
 172 
 173   void monitor_wait()                      { check_and_reset_count(); _monitor_wait_count++; }
 174   void monitor_wait_begin()                { check_and_reset_timer(); _monitor_wait_timer.start(); }
 175   void monitor_wait_end()                  { _monitor_wait_timer.stop(); check_and_reset_timer(); }
 176 
 177   void thread_sleep()                      { check_and_reset_count(); _sleep_count++; }
 178   void thread_sleep_begin()                { check_and_reset_timer(); _sleep_timer.start(); }
 179   void thread_sleep_end()                  { _sleep_timer.stop(); check_and_reset_timer(); }
 180 
 181   void contended_enter()                   { check_and_reset_count(); _contended_enter_count++; }
 182   void contended_enter_begin()             { check_and_reset_timer(); _contended_enter_timer.start(); }
 183   void contended_enter_end()               { _contended_enter_timer.stop(); check_and_reset_timer(); }
 184 
 185   void reset_count_stat()                  { _count_pending_reset = true; }
 186   void reset_time_stat()                   { _timer_pending_reset = true; }
 187 
 188   int* perf_recursion_counts_addr()        { return _perf_recursion_counts; }
 189   elapsedTimer* perf_timers_addr()         { return _perf_timers; }
 190 };
 191 
 192 // Thread snapshot to represent the thread state and statistics
 193 class ThreadSnapshot : public CHeapObj<mtInternal> {
 194 private:
 195   // This JavaThread* is protected by being stored in objects that are
 196   // protected by a ThreadsListSetter (ThreadDumpResult).
 197   JavaThread* _thread;
 198   oop         _threadObj;
 199   java_lang_Thread::ThreadStatus _thread_status;
 200 
 201   bool    _is_ext_suspended;
 202   bool    _is_in_native;
 203 
 204   jlong   _contended_enter_ticks;
 205   jlong   _contended_enter_count;
 206   jlong   _monitor_wait_ticks;
 207   jlong   _monitor_wait_count;
 208   jlong   _sleep_ticks;
 209   jlong   _sleep_count;
 210   oop     _blocker_object;
 211   oop     _blocker_object_owner;
 212 
 213   ThreadStackTrace*      _stack_trace;
 214   ThreadConcurrentLocks* _concurrent_locks;
 215   ThreadSnapshot*        _next;
 216 
 217   // ThreadSnapshot instances should only be created via
 218   // ThreadDumpResult::add_thread_snapshot.
 219   friend class ThreadDumpResult;
 220   ThreadSnapshot() : _thread(NULL), _threadObj(NULL),
 221                      _blocker_object(NULL), _blocker_object_owner(NULL),
 222                      _stack_trace(NULL), _concurrent_locks(NULL), _next(NULL) {};
 223   void        initialize(ThreadsList * t_list, JavaThread* thread);
 224 
 225 public:
 226   ~ThreadSnapshot();
 227 
 228   java_lang_Thread::ThreadStatus thread_status() { return _thread_status; }
 229 
 230   oop         threadObj() const           { return _threadObj; }
 231 
 232   void        set_next(ThreadSnapshot* n) { _next = n; }
 233 
 234   bool        is_ext_suspended()          { return _is_ext_suspended; }
 235   bool        is_in_native()              { return _is_in_native; }
 236 
 237   jlong       contended_enter_count()     { return _contended_enter_count; }
 238   jlong       contended_enter_ticks()     { return _contended_enter_ticks; }
 239   jlong       monitor_wait_count()        { return _monitor_wait_count; }
 240   jlong       monitor_wait_ticks()        { return _monitor_wait_ticks; }
 241   jlong       sleep_count()               { return _sleep_count; }
 242   jlong       sleep_ticks()               { return _sleep_ticks; }
 243 
 244 
 245   oop         blocker_object()            { return _blocker_object; }
 246   oop         blocker_object_owner()      { return _blocker_object_owner; }
 247 
 248   ThreadSnapshot*   next() const          { return _next; }
 249   ThreadStackTrace* get_stack_trace()     { return _stack_trace; }
 250   ThreadConcurrentLocks* get_concurrent_locks()     { return _concurrent_locks; }
 251 
 252   void        dump_stack_at_safepoint(int max_depth, bool with_locked_monitors);
 253   void        set_concurrent_locks(ThreadConcurrentLocks* l) { _concurrent_locks = l; }
 254   void        oops_do(OopClosure* f);
 255   void        metadata_do(void f(Metadata*));
 256 };
 257 
 258 class ThreadStackTrace : public CHeapObj<mtInternal> {
 259  private:
 260   JavaThread*                     _thread;
 261   int                             _depth;  // number of stack frames added
 262   bool                            _with_locked_monitors;
 263   GrowableArray<StackFrameInfo*>* _frames;
 264   GrowableArray<oop>*             _jni_locked_monitors;
 265 
 266  public:
 267 
 268   ThreadStackTrace(JavaThread* thread, bool with_locked_monitors);
 269   ~ThreadStackTrace();
 270 
 271   JavaThread*     thread()              { return _thread; }
 272   StackFrameInfo* stack_frame_at(int i) { return _frames->at(i); }
 273   int             get_stack_depth()     { return _depth; }
 274 
 275   void            add_stack_frame(javaVFrame* jvf);
 276   void            dump_stack_at_safepoint(int max_depth);
 277   Handle          allocate_fill_stack_trace_element_array(TRAPS);
 278   void            oops_do(OopClosure* f);
 279   void            metadata_do(void f(Metadata*));
 280   GrowableArray<oop>* jni_locked_monitors() { return _jni_locked_monitors; }
 281   int             num_jni_locked_monitors() { return (_jni_locked_monitors != NULL ? _jni_locked_monitors->length() : 0); }
 282 
 283   bool            is_owned_monitor_on_stack(oop object);
 284   void            add_jni_locked_monitor(oop object) { _jni_locked_monitors->append(object); }
 285 };
 286 
 287 // StackFrameInfo for keeping Method* and bci during
 288 // stack walking for later construction of StackTraceElement[]
 289 // Java instances
 290 class StackFrameInfo : public CHeapObj<mtInternal> {
 291  private:
 292   Method*             _method;
 293   int                 _bci;
 294   GrowableArray<oop>* _locked_monitors; // list of object monitors locked by this frame
 295   // We need to save the mirrors in the backtrace to keep the class
 296   // from being unloaded while we still have this stack trace.
 297   oop                 _class_holder;
 298 
 299  public:
 300 
 301   StackFrameInfo(javaVFrame* jvf, bool with_locked_monitors);
 302   ~StackFrameInfo() {
 303     if (_locked_monitors != NULL) {
 304       delete _locked_monitors;
 305     }
 306   };
 307   Method*   method() const       { return _method; }
 308   int       bci()    const       { return _bci; }
 309   void      oops_do(OopClosure* f);
 310   void      metadata_do(void f(Metadata*));
 311 
 312   int       num_locked_monitors()       { return (_locked_monitors != NULL ? _locked_monitors->length() : 0); }
 313   GrowableArray<oop>* locked_monitors() { return _locked_monitors; }
 314 
 315   void      print_on(outputStream* st) const;
 316 };
 317 
 318 class ThreadConcurrentLocks : public CHeapObj<mtInternal> {
 319 private:
 320   GrowableArray<instanceOop>* _owned_locks;
 321   ThreadConcurrentLocks*      _next;
 322   // This JavaThread* is protected in one of two different ways
 323   // depending on the usage of the ThreadConcurrentLocks object:
 324   // 1) by being stored in objects that are only allocated and used at a
 325   // safepoint (ConcurrentLocksDump), or 2) by being stored in objects
 326   // that are protected by a ThreadsListSetter (ThreadSnapshot inside
 327   // ThreadDumpResult).
 328   JavaThread*                 _thread;
 329  public:
 330   ThreadConcurrentLocks(JavaThread* thread);
 331   ~ThreadConcurrentLocks();
 332 
 333   void                        add_lock(instanceOop o);
 334   void                        set_next(ThreadConcurrentLocks* n) { _next = n; }
 335   ThreadConcurrentLocks*      next() { return _next; }
 336   JavaThread*                 java_thread()                      { return _thread; }
 337   GrowableArray<instanceOop>* owned_locks()                      { return _owned_locks; }
 338   void                        oops_do(OopClosure* f);
 339 };
 340 
 341 class ConcurrentLocksDump : public StackObj {
 342  private:
 343   ThreadConcurrentLocks* _map;
 344   ThreadConcurrentLocks* _last;   // Last ThreadConcurrentLocks in the map
 345   bool                   _retain_map_on_free;
 346 
 347   void build_map(GrowableArray<oop>* aos_objects);
 348   void add_lock(JavaThread* thread, instanceOop o);
 349 
 350  public:
 351   ConcurrentLocksDump(bool retain_map_on_free) : _map(NULL), _last(NULL), _retain_map_on_free(retain_map_on_free) {
 352     assert(SafepointSynchronize::is_at_safepoint(), "Must be constructed at a safepoint.");
 353   };
 354   ConcurrentLocksDump() : _map(NULL), _last(NULL), _retain_map_on_free(false) {
 355     assert(SafepointSynchronize::is_at_safepoint(), "Must be constructed at a safepoint.");
 356   };
 357   ~ConcurrentLocksDump();
 358 
 359   void                        dump_at_safepoint();
 360   ThreadConcurrentLocks*      thread_concurrent_locks(JavaThread* thread);
 361   void                        print_locks_on(JavaThread* t, outputStream* st);
 362 };
 363 
 364 class ThreadDumpResult : public StackObj {
 365  private:
 366   int                  _num_threads;
 367   int                  _num_snapshots;
 368   ThreadSnapshot*      _snapshots;
 369   ThreadSnapshot*      _last;
 370   ThreadDumpResult*    _next;
 371   ThreadsListSetter    _setter;  // Helper to set hazard ptr in the originating thread
 372                                  // which protects the JavaThreads in _snapshots.
 373 
 374   void                 link_thread_snapshot(ThreadSnapshot* ts);
 375 
 376  public:
 377   ThreadDumpResult();
 378   ThreadDumpResult(int num_threads);
 379   ~ThreadDumpResult();
 380 
 381   ThreadSnapshot*      add_thread_snapshot();
 382   ThreadSnapshot*      add_thread_snapshot(JavaThread* thread);
 383 
 384   void                 set_next(ThreadDumpResult* next) { _next = next; }
 385   ThreadDumpResult*    next()                           { return _next; }
 386   int                  num_threads()                    { return _num_threads; }
 387   int                  num_snapshots()                  { return _num_snapshots; }
 388   ThreadSnapshot*      snapshots()                      { return _snapshots; }
 389   void                 set_t_list()                     { _setter.set(); }
 390   ThreadsList*         t_list();
 391   bool                 t_list_has_been_set()            { return _setter.is_set(); }
 392   void                 oops_do(OopClosure* f);
 393   void                 metadata_do(void f(Metadata*));
 394 };
 395 
 396 class DeadlockCycle : public CHeapObj<mtInternal> {
 397  private:
 398   bool _is_deadlock;
 399   GrowableArray<JavaThread*>* _threads;
 400   DeadlockCycle*              _next;
 401  public:
 402   DeadlockCycle();
 403   ~DeadlockCycle();
 404 
 405   DeadlockCycle* next()                     { return _next; }
 406   void           set_next(DeadlockCycle* d) { _next = d; }
 407   void           add_thread(JavaThread* t)  { _threads->append(t); }
 408   void           reset()                    { _is_deadlock = false; _threads->clear(); }
 409   void           set_deadlock(bool value)   { _is_deadlock = value; }
 410   bool           is_deadlock()              { return _is_deadlock; }
 411   int            num_threads()              { return _threads->length(); }
 412   GrowableArray<JavaThread*>* threads()     { return _threads; }
 413   void           print_on_with(ThreadsList * t_list, outputStream* st) const;
 414 };
 415 
 416 // Utility class to get list of java threads.
 417 class ThreadsListEnumerator : public StackObj {
 418 private:
 419   GrowableArray<instanceHandle>* _threads_array;
 420 public:
 421   ThreadsListEnumerator(Thread* cur_thread,
 422                         bool include_jvmti_agent_threads = false,
 423                         bool include_jni_attaching_threads = true);
 424   int            num_threads()            { return _threads_array->length(); }
 425   instanceHandle get_threadObj(int index) { return _threads_array->at(index); }
 426 };
 427 
 428 
 429 // abstract utility class to set new thread states, and restore previous after the block exits
 430 class JavaThreadStatusChanger : public StackObj {
 431  private:
 432   java_lang_Thread::ThreadStatus _old_state;
 433   JavaThread*  _java_thread;
 434   bool _is_alive;
 435 
 436   void save_old_state(JavaThread* java_thread) {
 437     _java_thread  = java_thread;
 438     _is_alive = is_alive(java_thread);
 439     if (is_alive()) {
 440       _old_state = java_lang_Thread::get_thread_status(_java_thread->threadObj());
 441     }
 442   }
 443 
 444  public:
 445   static void set_thread_status(JavaThread* java_thread,
 446                                 java_lang_Thread::ThreadStatus state) {
 447     java_lang_Thread::set_thread_status(java_thread->threadObj(), state);
 448   }
 449 
 450   void set_thread_status(java_lang_Thread::ThreadStatus state) {
 451     if (is_alive()) {
 452       set_thread_status(_java_thread, state);
 453     }
 454   }
 455 
 456   JavaThreadStatusChanger(JavaThread* java_thread,
 457                           java_lang_Thread::ThreadStatus state) : _old_state(java_lang_Thread::NEW) {
 458     save_old_state(java_thread);
 459     set_thread_status(state);
 460   }
 461 
 462   JavaThreadStatusChanger(JavaThread* java_thread) : _old_state(java_lang_Thread::NEW) {
 463     save_old_state(java_thread);
 464   }
 465 
 466   ~JavaThreadStatusChanger() {
 467     set_thread_status(_old_state);
 468   }
 469 
 470   static bool is_alive(JavaThread* java_thread) {
 471     return java_thread != NULL && java_thread->threadObj() != NULL;
 472   }
 473 
 474   bool is_alive() {
 475     return _is_alive;
 476   }
 477 };
 478 
 479 // Change status to waiting on an object  (timed or indefinite)
 480 class JavaThreadInObjectWaitState : public JavaThreadStatusChanger {
 481  private:
 482   ThreadStatistics* _stat;
 483   bool _active;
 484 
 485  public:
 486   JavaThreadInObjectWaitState(JavaThread *java_thread, bool timed) :
 487     JavaThreadStatusChanger(java_thread,
 488                             timed ? java_lang_Thread::IN_OBJECT_WAIT_TIMED : java_lang_Thread::IN_OBJECT_WAIT) {
 489     if (is_alive()) {
 490       _stat = java_thread->get_thread_stat();
 491       _active = ThreadService::is_thread_monitoring_contention();
 492       _stat->monitor_wait();
 493       if (_active) {
 494         _stat->monitor_wait_begin();
 495       }
 496     } else {
 497       _active = false;
 498     }
 499   }
 500 
 501   ~JavaThreadInObjectWaitState() {
 502     if (_active) {
 503       _stat->monitor_wait_end();
 504     }
 505   }
 506 };
 507 
 508 // Change status to parked (timed or indefinite)
 509 class JavaThreadParkedState : public JavaThreadStatusChanger {
 510  private:
 511   ThreadStatistics* _stat;
 512   bool _active;
 513 
 514  public:
 515   JavaThreadParkedState(JavaThread *java_thread, bool timed) :
 516     JavaThreadStatusChanger(java_thread,
 517                             timed ? java_lang_Thread::PARKED_TIMED : java_lang_Thread::PARKED) {
 518     if (is_alive()) {
 519       _stat = java_thread->get_thread_stat();
 520       _active = ThreadService::is_thread_monitoring_contention();
 521       _stat->monitor_wait();
 522       if (_active) {
 523         _stat->monitor_wait_begin();
 524       }
 525     } else {
 526       _active = false;
 527     }
 528   }
 529 
 530   ~JavaThreadParkedState() {
 531     if (_active) {
 532       _stat->monitor_wait_end();
 533     }
 534   }
 535 };
 536 
 537 // Change status to blocked on (re-)entering a synchronization block
 538 class JavaThreadBlockedOnMonitorEnterState : public JavaThreadStatusChanger {
 539  private:
 540   ThreadStatistics* _stat;
 541   bool _active;
 542 
 543   static bool contended_enter_begin(JavaThread *java_thread) {
 544     set_thread_status(java_thread, java_lang_Thread::BLOCKED_ON_MONITOR_ENTER);
 545     ThreadStatistics* stat = java_thread->get_thread_stat();
 546     stat->contended_enter();
 547     bool active = ThreadService::is_thread_monitoring_contention();
 548     if (active) {
 549       stat->contended_enter_begin();
 550     }
 551     return active;
 552   }
 553 
 554  public:
 555   // java_thread is waiting thread being blocked on monitor reenter.
 556   // Current thread is the notifying thread which holds the monitor.
 557   static bool wait_reenter_begin(JavaThread *java_thread, ObjectMonitor *obj_m) {
 558     assert((java_thread != NULL), "Java thread should not be null here");
 559     bool active = false;
 560     if (is_alive(java_thread)) {
 561       active = contended_enter_begin(java_thread);
 562     }
 563     return active;
 564   }
 565 
 566   static void wait_reenter_end(JavaThread *java_thread, bool active) {
 567     if (active) {
 568       java_thread->get_thread_stat()->contended_enter_end();
 569     }
 570     set_thread_status(java_thread, java_lang_Thread::RUNNABLE);
 571   }
 572 
 573   JavaThreadBlockedOnMonitorEnterState(JavaThread *java_thread, ObjectMonitor *obj_m) :
 574     JavaThreadStatusChanger(java_thread), _stat(NULL), _active(false) {
 575     assert((java_thread != NULL), "Java thread should not be null here");
 576     // Change thread status and collect contended enter stats for monitor contended
 577     // enter done for external java world objects and it is contended. All other cases
 578     // like for vm internal objects and for external objects which are not contended
 579     // thread status is not changed and contended enter stat is not collected.
 580     _active = false;
 581     if (is_alive() && obj_m->contentions() > 0) {
 582       _stat = java_thread->get_thread_stat();
 583       _active = contended_enter_begin(java_thread);
 584     }
 585   }
 586 
 587   ~JavaThreadBlockedOnMonitorEnterState() {
 588     if (_active) {
 589       _stat->contended_enter_end();
 590     }
 591   }
 592 };
 593 
 594 // Change status to sleeping
 595 class JavaThreadSleepState : public JavaThreadStatusChanger {
 596  private:
 597   ThreadStatistics* _stat;
 598   bool _active;
 599  public:
 600   JavaThreadSleepState(JavaThread *java_thread) :
 601     JavaThreadStatusChanger(java_thread, java_lang_Thread::SLEEPING) {
 602     if (is_alive()) {
 603       _stat = java_thread->get_thread_stat();
 604       _active = ThreadService::is_thread_monitoring_contention();
 605       _stat->thread_sleep();
 606       if (_active) {
 607         _stat->thread_sleep_begin();
 608       }
 609     } else {
 610       _active = false;
 611     }
 612   }
 613 
 614   ~JavaThreadSleepState() {
 615     if (_active) {
 616       _stat->thread_sleep_end();
 617     }
 618   }
 619 };
 620 
 621 #endif // SHARE_SERVICES_THREADSERVICE_HPP