Skip to content

Commit

Permalink
Merge pull request #94 from javasoze/development
Browse files Browse the repository at this point in the history
added cleanup for jmxreporter
  • Loading branch information
codahale committed Oct 18, 2011
2 parents 1905711 + 1bbd02d commit a9bebab
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
6 changes: 6 additions & 0 deletions metrics-core/src/main/java/com/yammer/metrics/Metrics.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ public class Metrics {
JmxReporter.startDefault(DEFAULT_REGISTRY);
// make sure we initialize this so it can monitor GC etc
VirtualMachineMetrics.daemonThreadCount();

Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
JmxReporter.shutdownDefault();
}
});
}}

private Metrics() { /* unused */ }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,11 @@ protected AbstractReporter(MetricsRegistry metricsRegistry, String name) {
* @param unit the time unit of {@code period}
*/
public abstract void start(long period, TimeUnit unit);

/**
* Stops and cleans up reporter output
*/
public void shutdown(){

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand All @@ -29,6 +30,7 @@
*/
public class JmxReporter extends AbstractReporter {
private final Map<MetricName, MetricMBean> beans;
private final List<ObjectName> registeredBeans = new LinkedList<ObjectName>();
private final MBeanServer server;

public static interface MetricMBean {
Expand Down Expand Up @@ -306,6 +308,12 @@ public static final void startDefault(MetricsRegistry defaultMetricsRegistry) {
INSTANCE = new JmxReporter(defaultMetricsRegistry);
INSTANCE.start(1, TimeUnit.MINUTES);
}

public static final void shutdownDefault(){
if (INSTANCE!=null){
INSTANCE.shutdown();
}
}

public JmxReporter(MetricsRegistry metricsRegistry) {
super(metricsRegistry, "jmx-reporter");
Expand Down Expand Up @@ -353,6 +361,20 @@ public void run() {
private void registerBean(MetricName name, MetricMBean bean, ObjectName objectName) throws MBeanRegistrationException, InstanceAlreadyExistsException, NotCompliantMBeanException {
beans.put(name, bean);
server.registerMBean(bean, objectName);
registeredBeans.add(objectName);
}

@Override
public void shutdown(){
for (ObjectName name : registeredBeans){
try{
server.unregisterMBean(name);
}
catch(Exception ignored){

}
}
registeredBeans.clear();
}

}

0 comments on commit a9bebab

Please sign in to comment.