Skip to content

Commit 401e622

Browse files
Cache management bean objects
1 parent 815eeba commit 401e622

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

src/jvm_alloc_rate_meter/MeterThread.java

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,20 @@
22

33
import com.sun.management.ThreadMXBean;
44
import java.math.BigInteger;
5+
import java.util.List;
56
import java.util.function.LongConsumer;
7+
import java.lang.management.MemoryMXBean;
68
import java.lang.management.GarbageCollectorMXBean;
79
import java.lang.management.ManagementFactory;
810

911
public class MeterThread extends Thread {
1012

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;
1319

1420
private volatile boolean doRun = true;
1521

@@ -19,6 +25,11 @@ public MeterThread(LongConsumer callback) {
1925

2026
public MeterThread(LongConsumer callback, int intervalMs) {
2127
super("jvm-alloc-rate-meter-thread");
28+
29+
this.memoryBean = ManagementFactory.getMemoryMXBean();
30+
this.threadBean = (ThreadMXBean)ManagementFactory.getThreadMXBean();
31+
this.gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
32+
2233
this.callback = callback;
2334
this.intervalMs = intervalMs;
2435
setDaemon(true);
@@ -80,24 +91,23 @@ public void terminate() {
8091
doRun = false;
8192
}
8293

83-
private static long usedHeap() {
84-
return ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
94+
private long usedHeap() {
95+
return memoryBean.getHeapMemoryUsage().getUsed();
8596
}
8697

8798
/** Returns total number of GC cycles since the start of the VM. **/
88-
private static long gcCounts() {
99+
private long gcCounts() {
89100
long total = 0;
90-
for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
101+
for (GarbageCollectorMXBean bean : gcBeans) {
91102
total += bean.getCollectionCount();
92103
}
93104
return total;
94105
}
95106

96107
/** 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);
101111
BigInteger result = BigInteger.ZERO;
102112
// This is not correct because we will lose allocation data from threads
103113
// that died. Oh well.

0 commit comments

Comments
 (0)