Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.codahale.metrics;
  
  import java.util.*;
A registry of metric instances.
 
 public class MetricRegistry implements MetricSet {
    
Concatenates elements to form a dotted name, eliding any null values or empty strings.

Parameters:
name the first element of the name
names the remaining elements of the name
Returns:
name and names concatenated by periods
 
     public static String name(String nameString... names) {
         final StringBuilder builder = new StringBuilder();
         append(buildername);
         if (names != null) {
             for (String s : names) {
                 append(builders);
             }
         }
         return builder.toString();
     }

    
Concatenates a class name and elements to form a dotted name, eliding any null values or empty strings.

Parameters:
klass the first element of the name
names the remaining elements of the name
Returns:
klass and names concatenated by periods
 
     public static String name(Class<?> klassString... names) {
         return name(klass.getName(), names);
     }
 
     private static void append(StringBuilder builderString part) {
         if (part != null && !part.isEmpty()) {
             if (builder.length() > 0) {
                 builder.append('.');
             }
             builder.append(part);
         }
     }
 
     private final ConcurrentMap<StringMetricmetrics;
     private final List<MetricRegistryListenerlisteners;

    
Creates a new MetricRegistry.
 
     public MetricRegistry() {
         this. = buildMap();
         this. = new CopyOnWriteArrayList<MetricRegistryListener>();
     }

    
Creates a new java.util.concurrent.ConcurrentMap implementation for use inside the registry. Override this to create a MetricRegistry with space- or time-bounded metric lifecycles, for example.

 
     protected ConcurrentMap<StringMetricbuildMap() {
         return new ConcurrentHashMap<StringMetric>();
     }

    
Given a Metric, registers it under the given name.

Parameters:
name the name of the metric
metric the metric
<T> the type of the metric
Returns:
metric
Throws:
java.lang.IllegalArgumentException if the name is already registered
 
     @SuppressWarnings("unchecked")
     public <T extends Metric> T register(String name, T metricthrows IllegalArgumentException {
         if (metric instanceof MetricSet) {
             registerAll(name, (MetricSetmetric);
         } else {
             final Metric existing = .putIfAbsent(namemetric);
             if (existing == null) {
                 onMetricAdded(namemetric);
             } else {
                 throw new IllegalArgumentException("A metric named " + name + " already exists");
             }
         }
         return metric;
     }

    
Given a metric set, registers them.

Parameters:
metrics a set of metrics
Throws:
java.lang.IllegalArgumentException if any of the names are already registered
    public void registerAll(MetricSet metricsthrows IllegalArgumentException {
        registerAll(nullmetrics);
    }

    
Creates a new Counter and registers it under the given name.

Parameters:
name the name of the metric
Returns:
a new Counter
    public Counter counter(String name) {
        return getOrAdd(name.);
    }

    
Creates a new Histogram and registers it under the given name.

Parameters:
name the name of the metric
Returns:
a new Histogram
    public Histogram histogram(String name) {
        return getOrAdd(name.);
    }

    
Creates a new Meter and registers it under the given name.

Parameters:
name the name of the metric
Returns:
a new Meter
    public Meter meter(String name) {
        return getOrAdd(name.);
    }

    
Creates a new Timer and registers it under the given name.

Parameters:
name the name of the metric
Returns:
a new Timer
    public Timer timer(String name) {
        return getOrAdd(name.);
    }

    
Removes the metric with the given name.

Parameters:
name the name of the metric
Returns:
whether or not the metric was removed
    public boolean remove(String name) {
        final Metric metric = .remove(name);
        if (metric != null) {
            onMetricRemoved(namemetric);
            return true;
        }
        return false;
    }

    
Removes all metrics which match the given filter.

Parameters:
filter a filter
    public void removeMatching(MetricFilter filter) {
        for (Map.Entry<StringMetricentry : .entrySet()) {
            if (filter.matches(entry.getKey(), entry.getValue())) {
                remove(entry.getKey());
            }
        }
    }

    
Adds a MetricRegistryListener to a collection of listeners that will be notified on metric creation. Listeners will be notified in the order in which they are added.

N.B.: The listener will be notified of all existing metrics when it first registers.

Parameters:
listener the listener that will be notified
    public void addListener(MetricRegistryListener listener) {
        .add(listener);
        for (Map.Entry<StringMetricentry : .entrySet()) {
            notifyListenerOfAddedMetric(listenerentry.getValue(), entry.getKey());
        }
    }

    
Removes a MetricRegistryListener from this registry's collection of listeners.

Parameters:
listener the listener that will be removed
    public void removeListener(MetricRegistryListener listener) {
        .remove(listener);
    }

    
Returns a set of the names of all the metrics in the registry.

Returns:
the names of all the metrics
    public SortedSet<StringgetNames() {
        return Collections.unmodifiableSortedSet(new TreeSet<String>(.keySet()));
    }

    
Returns a map of all the gauges in the registry and their names.

Returns:
all the gauges in the registry
    public SortedMap<StringGaugegetGauges() {
        return getGauges(.);
    }

    
Returns a map of all the gauges in the registry and their names which match the given filter.

Parameters:
filter the metric filter to match
Returns:
all the gauges in the registry
    public SortedMap<StringGaugegetGauges(MetricFilter filter) {
        return getMetrics(Gauge.classfilter);
    }

    
Returns a map of all the counters in the registry and their names.

Returns:
all the counters in the registry
    public SortedMap<StringCountergetCounters() {
        return getCounters(.);
    }

    
Returns a map of all the counters in the registry and their names which match the given filter.

Parameters:
filter the metric filter to match
Returns:
all the counters in the registry
    public SortedMap<StringCountergetCounters(MetricFilter filter) {
        return getMetrics(Counter.classfilter);
    }

    
Returns a map of all the histograms in the registry and their names.

Returns:
all the histograms in the registry
    public SortedMap<StringHistogramgetHistograms() {
        return getHistograms(.);
    }

    
Returns a map of all the histograms in the registry and their names which match the given filter.

Parameters:
filter the metric filter to match
Returns:
all the histograms in the registry
    public SortedMap<StringHistogramgetHistograms(MetricFilter filter) {
        return getMetrics(Histogram.classfilter);
    }

    
Returns a map of all the meters in the registry and their names.

Returns:
all the meters in the registry
    public SortedMap<StringMetergetMeters() {
        return getMeters(.);
    }

    
Returns a map of all the meters in the registry and their names which match the given filter.

Parameters:
filter the metric filter to match
Returns:
all the meters in the registry
    public SortedMap<StringMetergetMeters(MetricFilter filter) {
        return getMetrics(Meter.classfilter);
    }

    
Returns a map of all the timers in the registry and their names.

Returns:
all the timers in the registry
    public SortedMap<StringTimergetTimers() {
        return getTimers(.);
    }

    
Returns a map of all the timers in the registry and their names which match the given filter.

Parameters:
filter the metric filter to match
Returns:
all the timers in the registry
    public SortedMap<StringTimergetTimers(MetricFilter filter) {
        return getMetrics(Timer.classfilter);
    }
    @SuppressWarnings("unchecked")
    private <T extends Metric> T getOrAdd(String nameMetricBuilder<T> builder) {
        final Metric metric = .get(name);
        if (builder.isInstance(metric)) {
            return (T) metric;
        } else if (metric == null) {
            try {
                return register(namebuilder.newMetric());
            } catch (IllegalArgumentException e) {
                final Metric added = .get(name);
                if (builder.isInstance(added)) {
                    return (T) added;
                }
            }
        }
        throw new IllegalArgumentException(name + " is already used for a different type of metric");
    }
    @SuppressWarnings("unchecked")
    private <T extends MetricSortedMap<String, T> getMetrics(Class<T> klassMetricFilter filter) {
        final TreeMap<String, T> timers = new TreeMap<String, T>();
        for (Map.Entry<StringMetricentry : .entrySet()) {
            if (klass.isInstance(entry.getValue()) && filter.matches(entry.getKey(),
                                                                     entry.getValue())) {
                timers.put(entry.getKey(), (T) entry.getValue());
            }
        }
        return Collections.unmodifiableSortedMap(timers);
    }
    private void onMetricAdded(String nameMetric metric) {
        for (MetricRegistryListener listener : ) {
            notifyListenerOfAddedMetric(listenermetricname);
        }
    }
    private void notifyListenerOfAddedMetric(MetricRegistryListener listenerMetric metricString name) {
        if (metric instanceof Gauge) {
            listener.onGaugeAdded(name, (Gauge<?>) metric);
        } else if (metric instanceof Counter) {
            listener.onCounterAdded(name, (Countermetric);
        } else if (metric instanceof Histogram) {
            listener.onHistogramAdded(name, (Histogrammetric);
        } else if (metric instanceof Meter) {
            listener.onMeterAdded(name, (Metermetric);
        } else if (metric instanceof Timer) {
            listener.onTimerAdded(name, (Timermetric);
        } else {
            throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
        }
    }
    private void onMetricRemoved(String nameMetric metric) {
        for (MetricRegistryListener listener : ) {
            notifyListenerOfRemovedMetric(namemetriclistener);
        }
    }
    private void notifyListenerOfRemovedMetric(String nameMetric metricMetricRegistryListener listener) {
        if (metric instanceof Gauge) {
            listener.onGaugeRemoved(name);
        } else if (metric instanceof Counter) {
            listener.onCounterRemoved(name);
        } else if (metric instanceof Histogram) {
            listener.onHistogramRemoved(name);
        } else if (metric instanceof Meter) {
            listener.onMeterRemoved(name);
        } else if (metric instanceof Timer) {
            listener.onTimerRemoved(name);
        } else {
            throw new IllegalArgumentException("Unknown metric type: " + metric.getClass());
        }
    }
    private void registerAll(String prefixMetricSet metricsthrows IllegalArgumentException {
        for (Map.Entry<StringMetricentry : metrics.getMetrics().entrySet()) {
            if (entry.getValue() instanceof MetricSet) {
                registerAll(name(prefixentry.getKey()), (MetricSetentry.getValue());
            } else {
                register(name(prefixentry.getKey()), entry.getValue());
            }
        }
    }
    @Override
    public Map<StringMetricgetMetrics() {
        return Collections.unmodifiableMap();
    }

    
A quick and easy way of capturing the notion of default metrics.
    private interface MetricBuilder<T extends Metric> {
        MetricBuilder<CounterCOUNTERS = new MetricBuilder<Counter>() {
            @Override
            public Counter newMetric() {
                return new Counter();
            }
            @Override
            public boolean isInstance(Metric metric) {
                return Counter.class.isInstance(metric);
            }
        };
            @Override
            public Histogram newMetric() {
                return new Histogram(new ExponentiallyDecayingReservoir());
            }
            @Override
            public boolean isInstance(Metric metric) {
                return Histogram.class.isInstance(metric);
            }
        };
        MetricBuilder<MeterMETERS = new MetricBuilder<Meter>() {
            @Override
            public Meter newMetric() {
                return new Meter();
            }
            @Override
            public boolean isInstance(Metric metric) {
                return Meter.class.isInstance(metric);
            }
        };
        MetricBuilder<TimerTIMERS = new MetricBuilder<Timer>() {
            @Override
            public Timer newMetric() {
                return new Timer();
            }
            @Override
            public boolean isInstance(Metric metric) {
                return Timer.class.isInstance(metric);
            }
        };
        T newMetric();
        boolean isInstance(Metric metric);
    }
New to GrepCode? Check out our FAQ X