All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.librato.metrics.reporter.DeltaTracker Maven / Gradle / Ivy

Go to download

The LibratoReporter class runs in the background, publishing metrics to the Librato Metrics API at the specified interval.

The newest version!
package com.librato.metrics.reporter;

import com.codahale.metrics.Histogram;
import com.codahale.metrics.Metered;
import com.codahale.metrics.Metric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Tracks the last named value.
 */
public class DeltaTracker {
    private static final Logger LOG = LoggerFactory.getLogger(DeltaTracker.class);
    private final ConcurrentMap lookup = new ConcurrentHashMap();

    public interface MetricSupplier {
        Map getMetrics();
    }

    public DeltaTracker() {
        this(new MetricSupplier() {
            public Map getMetrics() {
                return new HashMap();
            }
        });
    }

    public DeltaTracker(MetricSupplier supplier) {
        for (Map.Entry entry : supplier.getMetrics().entrySet()) {
            final String name = entry.getKey();
            final Metric metric = entry.getValue();
            if (metric instanceof Metered) {
                lookup.put(name, ((Metered) metric).getCount());
            }
            if (metric instanceof Histogram) {
                lookup.put(name, ((Histogram) metric).getCount());
            }
        }
    }

    /**
     * Gets the delta without updating the internal data store
     */
    public Long peekDelta(String name, long count) {
        Long previous = lookup.get(name);
        return calculateDelta(name, previous, count);
    }

    /**
     * Calculates the delta.  If this is a new value that has not been seen before, zero will be assumed to be the
     * initial value. Updates the internal map with the supplied count.
     *
     * @param name  the name of the counter
     * @param count the counter value
     * @return the delta
     */
    public Long getDelta(String name, long count) {
        Long previous = lookup.put(name, count);
        return calculateDelta(name, previous, count);
    }

    private Long calculateDelta(String name, Long previous, long count) {
        if (previous == null) {
            previous = 0L;
        } else if (count < previous) {
            LOG.debug("Saw a non-monotonically increasing value for metric {}", name);
            previous = 0L;
        }
        return count - previous;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy