Metrics学习02 – Counter

Counter是要学习的Metrics的第二个工具，顾名思义即是计数器，通常用来执行统计之类的工作。
Counter比Gauge也复杂不了多少，直接看代码好了：

public class CounterShow {

public static void main(String[] args) {

final MetricRegistry metrics = new MetricRegistry();
final ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics).build();
reporter.start(3, TimeUnit.SECONDS);

Counter counter = metrics.counter("异常监控");

for (int i = 0; i < 100; i++) {
try {
if (0 == i % 3) {
throw new RuntimeException("自定义异常");
}
TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
counter.inc();
}
}
}
}


counter
(
)

MetricRegistry的实例为各种指标工具都提供了快速创建实例的方法，通过MetricRegistry提供的方法创建完成指标实例后可以自动完成注册。所以在上面的代码中没有再显式地将counter实例注册到MetricRegistry中。

    public void increment() {
}

Cell[] as; long b, v; int m; Cell a;
if ((as = cells) != null || !casBase(b = base, b + x)) {// 如cells不为空，直接对cells操作；否则casBase
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[getProbe() & m]) == null ||
!(uncontended = a.cas(v = a.value, v + x)))    // CAS cell
longAccumulate(x, null, uncontended);    // 创建新的Cell或者扩容
}
}


19-6-24 22:18:37 ===============================================================
-- Counters --------------------------------------------------------------------

count = 2

19-6-24 22:18:40 ===============================================================
-- Counters --------------------------------------------------------------------

count = 3

19-6-24 22:18:43 ===============================================================
-- Counters --------------------------------------------------------------------

count = 5