View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
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  }