1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.monitoring.gauges;
18
19 import org.apache.commons.monitoring.Role;
20 import org.apache.commons.monitoring.store.DataStore;
21
22 import java.util.Map;
23 import java.util.Timer;
24 import java.util.TimerTask;
25 import java.util.concurrent.ConcurrentHashMap;
26
27 public final class DefaultGaugeManager implements GaugeManager {
28 private final Map<Role, Timer> timers = new ConcurrentHashMap<Role, Timer>();
29 private final DataStore store;
30
31 public DefaultGaugeManager(final DataStore dataStore) {
32 store = dataStore;
33 }
34
35 @Override
36 public void stop() {
37 for (final Timer timer : timers.values()) {
38 timer.cancel();
39 }
40 timers.clear();
41 }
42
43 @Override
44 public void stopGauge(final Role role) {
45 final Timer timer = timers.remove(role);
46 if (timer != null) {
47 timer.cancel();
48 }
49 }
50
51 @Override
52 public void addGauge(final Gauge gauge) {
53 final Role role = gauge.role();
54
55 this.store.createOrNoopGauge(role);
56
57 final Timer timer = new Timer("gauge-" + role.getName() + "-timer", true);
58 timers.put(role, timer);
59 timer.scheduleAtFixedRate(new GaugeTask(store, gauge), 0, gauge.period());
60 }
61
62 private static class GaugeTask extends TimerTask {
63 private final Gauge gauge;
64 private final DataStore store;
65
66 public GaugeTask(final DataStore store, final Gauge gauge) {
67 this.store = store;
68 this.gauge = gauge;
69 }
70
71 @Override
72 public void run() {
73 store.addToGauge(gauge, System.currentTimeMillis(), gauge.value());
74 }
75 }
76 }