0
# Thread Monitoring
1
2
Real-time thread state tracking, deadlock detection, and thread dump generation with optional performance optimization through caching.
3
4
## Capabilities
5
6
### ThreadStatesGaugeSet
7
8
Monitors thread states and provides deadlock detection capabilities.
9
10
```java { .api }
11
/**
12
* A set of gauges for the number of threads in their various states and deadlock detection.
13
*/
14
public class ThreadStatesGaugeSet implements MetricSet {
15
/**
16
* Creates a new set of gauges using the default MXBeans.
17
*/
18
public ThreadStatesGaugeSet();
19
20
/**
21
* Creates a new set of gauges using the given MXBean and detector.
22
* @param threads a thread MXBean
23
* @param deadlockDetector a deadlock detector
24
*/
25
public ThreadStatesGaugeSet(ThreadMXBean threads, ThreadDeadlockDetector deadlockDetector);
26
27
/**
28
* Returns all thread-related metrics.
29
* @return map of metric names to Metric instances
30
*/
31
public Map<String, Metric> getMetrics();
32
}
33
```
34
35
### CachedThreadStatesGaugeSet
36
37
Performance-optimized version that caches ThreadInfo objects for a specified interval.
38
39
```java { .api }
40
/**
41
* A variation of ThreadStatesGaugeSet that caches the ThreadInfo[] objects for a given interval.
42
*/
43
public class CachedThreadStatesGaugeSet extends ThreadStatesGaugeSet {
44
/**
45
* Creates a new set of gauges using the default MXBeans with caching.
46
* @param interval cache interval
47
* @param unit cache interval time unit
48
*/
49
public CachedThreadStatesGaugeSet(long interval, TimeUnit unit);
50
51
/**
52
* Creates a new set of gauges using the given MXBean and detector with caching.
53
* @param threadMXBean a thread MXBean
54
* @param deadlockDetector a deadlock detector
55
* @param interval cache interval
56
* @param unit cache interval time unit
57
*/
58
public CachedThreadStatesGaugeSet(ThreadMXBean threadMXBean, ThreadDeadlockDetector deadlockDetector, long interval, TimeUnit unit);
59
}
60
```
61
62
### ThreadDeadlockDetector
63
64
Utility class for detecting and reporting thread deadlocks.
65
66
```java { .api }
67
/**
68
* A utility class for detecting deadlocked threads.
69
*/
70
public class ThreadDeadlockDetector {
71
/**
72
* Creates a new detector using the default ThreadMXBean.
73
*/
74
public ThreadDeadlockDetector();
75
76
/**
77
* Creates a new detector using the given ThreadMXBean.
78
* @param threads a ThreadMXBean
79
*/
80
public ThreadDeadlockDetector(ThreadMXBean threads);
81
82
/**
83
* Returns a set of diagnostic stack traces for any deadlocked threads.
84
* @return stack traces for deadlocked threads or an empty set
85
*/
86
public Set<String> getDeadlockedThreads();
87
}
88
```
89
90
### ThreadDump
91
92
Utility class for generating comprehensive thread dumps.
93
94
```java { .api }
95
/**
96
* A convenience class for getting a thread dump.
97
*/
98
public class ThreadDump {
99
/**
100
* Creates a new ThreadDump instance.
101
* @param threadMXBean the ThreadMXBean to use
102
*/
103
public ThreadDump(ThreadMXBean threadMXBean);
104
105
/**
106
* Dumps all threads' current information, including synchronization, to an output stream.
107
* @param out an output stream
108
*/
109
public void dump(OutputStream out);
110
111
/**
112
* Dumps all threads' current information with control over synchronization info.
113
* @param lockedMonitors dump all locked monitors if true
114
* @param lockedSynchronizers dump all locked ownable synchronizers if true
115
* @param out an output stream
116
*/
117
public void dump(boolean lockedMonitors, boolean lockedSynchronizers, OutputStream out);
118
}
119
```
120
121
**Metrics Provided by ThreadStatesGaugeSet:**
122
123
- **Thread State Counts**: `new.count`, `runnable.count`, `blocked.count`, `waiting.count`, `timed_waiting.count`, `terminated.count`
124
- **Thread Totals**: `count` (total threads), `daemon.count`, `peak.count`, `total_started.count`
125
- **Deadlock Detection**: `deadlock.count` (number of deadlocked threads), `deadlocks` (detailed deadlock information)
126
127
**Usage Examples:**
128
129
```java
130
import com.codahale.metrics.MetricRegistry;
131
import com.codahale.metrics.jvm.*;
132
import java.util.concurrent.TimeUnit;
133
134
// Basic thread monitoring
135
MetricRegistry registry = new MetricRegistry();
136
registry.registerAll(new ThreadStatesGaugeSet());
137
138
// Access thread metrics
139
Gauge<Integer> totalThreads = registry.getGauges().get("count");
140
Gauge<Integer> runnableThreads = registry.getGauges().get("runnable.count");
141
Gauge<Integer> deadlockCount = registry.getGauges().get("deadlock.count");
142
143
System.out.println("Total threads: " + totalThreads.getValue());
144
System.out.println("Runnable threads: " + runnableThreads.getValue());
145
System.out.println("Deadlocked threads: " + deadlockCount.getValue());
146
147
// Cached thread monitoring for better performance
148
registry.registerAll(new CachedThreadStatesGaugeSet(5, TimeUnit.SECONDS));
149
150
// Custom thread monitoring with specific beans
151
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
152
ThreadDeadlockDetector detector = new ThreadDeadlockDetector(threadBean);
153
registry.registerAll(new ThreadStatesGaugeSet(threadBean, detector));
154
155
// Direct deadlock detection
156
ThreadDeadlockDetector deadlockDetector = new ThreadDeadlockDetector();
157
Set<String> deadlocks = deadlockDetector.getDeadlockedThreads();
158
if (!deadlocks.isEmpty()) {
159
System.out.println("Deadlocks detected:");
160
deadlocks.forEach(System.out::println);
161
}
162
163
// Generate thread dump
164
ThreadDump threadDump = new ThreadDump(ManagementFactory.getThreadMXBean());
165
threadDump.dump(System.out); // Full dump with synchronization info
166
threadDump.dump(false, false, System.out); // Basic dump without sync info
167
```
168
169
**Performance Considerations:**
170
171
- Use `CachedThreadStatesGaugeSet` in high-frequency monitoring scenarios to reduce overhead
172
- Thread dump generation can be expensive; use sparingly in production
173
- Deadlock detection involves examining all threads; cache results when possible