metric instance per class instance or shared across instances?

258 views
Skip to first unread message

Ben McCann

unread,
Dec 16, 2013, 8:19:19 PM12/16/13
to metric...@googlegroups.com
Hi,

I've setup Guice dependency inject to provide a MetricRegistry as a Singleton. For the classes where I want to have metrics, do those metrics provider need to be singletons or will they share counters if registered with the same name? E.g. can I do the following:

    public class MailSender {

      private final Counter attemptCount;

      @Inject
      public MailSender(MetricRegistry metrics) {
        this.attemptCount = metrics.counter(MetricRegistry.name(MailSender .class, "attempts"));
      }

    }

This would create a new attemptCount Counter for everytime I create a MailSender to send an email, but those counters would all share the same MetricRegistry and the same name. Is that okay or do I need to make it static or a singleton so that all the MailSender instances share the same Counter?

Thanks,
Ben

Ryan Rupp

unread,
Dec 16, 2013, 11:58:33 PM12/16/13
to metric...@googlegroups.com
The methods on the MetricsRegistry such as counter, timer, meter etc. will return the existing metric if one has already been registered under that name so what you're doing is fine. For reference see - https://github.com/codahale/metrics/blob/master/metrics-core/src/main/java/com/codahale/metrics/MetricRegistry.java#L307 - which is use by all those methods.

Ben McCann

unread,
Dec 17, 2013, 12:06:03 AM12/17/13
to metric...@googlegroups.com
Thanks. Any advice on registering metrics computed from other metrics? While you can recreate simple metrics in constructors, it seems like I'll have to make all my metrics singletons in order to allow them to be used in calculating ratio gauges and other calculated metrics. E.g. I tried to do this and it didn't work:

    public class MailSender {

      private final Counter attemptCount;

      @Inject
      public MailSender(MetricRegistry metrics) {
        this.cacheHitCount = metrics.counter(MetricRegistry.name(MailSender .class, "cache-hits"));
        this.cacheAttemptCount = metrics.counter(MetricRegistry.name(MailSender .class, "cache-attempts"));
        metrics.register(MetricRegistry.name(MailSender.class, "cache-hit-ratio"),
            new HitRateGauge(cacheHitCount, cacheAttemptCount));
      }

    }



--
You received this message because you are subscribed to a topic in the Google Groups "metrics-user" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/metrics-user/k38U-nn80bk/unsubscribe.
To unsubscribe from this group and all its topics, send an email to metrics-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
about.me/benmccann
Reply all
Reply to author
Forward
0 new messages