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