2
2
3
3
import com .sun .management .ThreadMXBean ;
4
4
import java .math .BigInteger ;
5
+ import java .util .List ;
5
6
import java .util .function .LongConsumer ;
7
+ import java .lang .management .MemoryMXBean ;
6
8
import java .lang .management .GarbageCollectorMXBean ;
7
9
import java .lang .management .ManagementFactory ;
8
10
9
11
public class MeterThread extends Thread {
10
12
11
- private LongConsumer callback ;
12
- private int intervalMs ;
13
+ private final MemoryMXBean memoryBean ;
14
+ private final ThreadMXBean threadBean ;
15
+ private final List <GarbageCollectorMXBean > gcBeans ;
16
+
17
+ private final LongConsumer callback ;
18
+ private final int intervalMs ;
13
19
14
20
private volatile boolean doRun = true ;
15
21
@@ -19,6 +25,11 @@ public MeterThread(LongConsumer callback) {
19
25
20
26
public MeterThread (LongConsumer callback , int intervalMs ) {
21
27
super ("jvm-alloc-rate-meter-thread" );
28
+
29
+ this .memoryBean = ManagementFactory .getMemoryMXBean ();
30
+ this .threadBean = (ThreadMXBean )ManagementFactory .getThreadMXBean ();
31
+ this .gcBeans = ManagementFactory .getGarbageCollectorMXBeans ();
32
+
22
33
this .callback = callback ;
23
34
this .intervalMs = intervalMs ;
24
35
setDaemon (true );
@@ -80,24 +91,23 @@ public void terminate() {
80
91
doRun = false ;
81
92
}
82
93
83
- private static long usedHeap () {
84
- return ManagementFactory . getMemoryMXBean () .getHeapMemoryUsage ().getUsed ();
94
+ private long usedHeap () {
95
+ return memoryBean .getHeapMemoryUsage ().getUsed ();
85
96
}
86
97
87
98
/** Returns total number of GC cycles since the start of the VM. **/
88
- private static long gcCounts () {
99
+ private long gcCounts () {
89
100
long total = 0 ;
90
- for (GarbageCollectorMXBean bean : ManagementFactory . getGarbageCollectorMXBeans () ) {
101
+ for (GarbageCollectorMXBean bean : gcBeans ) {
91
102
total += bean .getCollectionCount ();
92
103
}
93
104
return total ;
94
105
}
95
106
96
107
/** Total allocation can overflow a long, so using BigInt here. **/
97
- private static BigInteger allocatedByAllThreads () {
98
- ThreadMXBean bean = (ThreadMXBean )ManagementFactory .getThreadMXBean ();
99
- long [] ids = bean .getAllThreadIds ();
100
- long [] allocatedBytes = bean .getThreadAllocatedBytes (ids );
108
+ private BigInteger allocatedByAllThreads () {
109
+ long [] ids = threadBean .getAllThreadIds ();
110
+ long [] allocatedBytes = threadBean .getThreadAllocatedBytes (ids );
101
111
BigInteger result = BigInteger .ZERO ;
102
112
// This is not correct because we will lose allocation data from threads
103
113
// that died. Oh well.
0 commit comments