1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.metrics;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22 import org.apache.hadoop.metrics.MetricsRecord;
23 import org.apache.hadoop.metrics.util.MetricsBase;
24 import org.apache.hadoop.metrics.util.MetricsRegistry;
25 import org.apache.hadoop.util.StringUtils;
26
27
28
29
30
31 public class MetricsRate extends MetricsBase {
32 private static final Log LOG = LogFactory.getLog("org.apache.hadoop.hbase.metrics");
33
34 private int value;
35 private float prevRate;
36 private long ts;
37
38 public MetricsRate(final String name, final MetricsRegistry registry,
39 final String description) {
40 super(name, description);
41 this.value = 0;
42 this.prevRate = 0;
43 this.ts = System.currentTimeMillis();
44 registry.add(name, this);
45 }
46
47 public MetricsRate(final String name, final MetricsRegistry registry) {
48 this(name, registry, NO_DESCRIPTION);
49 }
50
51 public synchronized void inc(final int incr) {
52 value += incr;
53 }
54
55 public synchronized void inc() {
56 value++;
57 }
58
59 private synchronized void intervalHeartBeat() {
60 long now = System.currentTimeMillis();
61 long diff = (now-ts)/1000;
62 if (diff == 0) diff = 1;
63 this.prevRate = (float)value / diff;
64 this.value = 0;
65 this.ts = now;
66 }
67
68 @Override
69 public synchronized void pushMetric(final MetricsRecord mr) {
70 intervalHeartBeat();
71 try {
72 mr.setMetric(getName(), getPreviousIntervalValue());
73 } catch (Exception e) {
74 LOG.info("pushMetric failed for " + getName() + "\n" +
75 StringUtils.stringifyException(e));
76 }
77 }
78
79 public synchronized float getPreviousIntervalValue() {
80 return this.prevRate;
81 }
82 }