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