com.alibaba.metrics.jvm.GarbageCollectorMetricSet Maven / Gradle / Ivy
The newest version!
package com.alibaba.metrics.jvm;
import com.alibaba.metrics.Metric;
import com.alibaba.metrics.MetricName;
import com.alibaba.metrics.MetricRegistry;
import com.alibaba.metrics.MetricSet;
import com.alibaba.metrics.PersistentGauge;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* A set of gauges for the counts and elapsed times of garbage collections.
*/
public class GarbageCollectorMetricSet implements MetricSet {
private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
private final List garbageCollectors;
private final List lastGarbageCountCollectors;
private final List lastGarbageTimeCollectors;
/**
* Creates a new set of gauges for all discoverable garbage collectors.
*/
public GarbageCollectorMetricSet() {
this(ManagementFactory.getGarbageCollectorMXBeans());
}
/**
* Creates a new set of gauges for the given collection of garbage collectors.
*
* @param garbageCollectors the garbage collectors
*/
public GarbageCollectorMetricSet(Collection garbageCollectors) {
this.garbageCollectors = new ArrayList(garbageCollectors);
this.lastGarbageCountCollectors = new ArrayList(){{
add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);
}};
this.lastGarbageTimeCollectors = new ArrayList(){{
add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);add(0L);
}};
}
@Override
public Map getMetrics() {
final Map gauges = new HashMap();
int index = 0;
for (final GarbageCollectorMXBean gc : garbageCollectors) {
final String name = WHITESPACE.matcher(gc.getName()).replaceAll("_").toLowerCase();
final int i = index;
gauges.put(MetricRegistry.name(name, "count"), new PersistentGauge() {
@Override
public Long getValue() {
return gc.getCollectionCount();
}
});
gauges.put(MetricRegistry.name(name, "time"), new PersistentGauge() {
@Override
public Long getValue() {
return gc.getCollectionTime();
}
});
gauges.put(MetricRegistry.name(name, "count.delta"), new PersistentGauge() {
@Override
public Long getValue() {
long current = gc.getCollectionCount();
long result = current - lastGarbageCountCollectors.get(i);
lastGarbageCountCollectors.set(i, current);
return result;
}
});
gauges.put(MetricRegistry.name(name, "time.delta"), new PersistentGauge() {
@Override
public Long getValue() {
long current = gc.getCollectionTime();
long result = current - lastGarbageTimeCollectors.get(i);
lastGarbageTimeCollectors.set(i, current);
return result;
}
});
index = i + 1;
}
return Collections.unmodifiableMap(gauges);
}
@Override
public long lastUpdateTime() {
return System.currentTimeMillis();
}
}