001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.monitoring.gauges; 018 019 import org.apache.commons.monitoring.Role; 020 import org.apache.commons.monitoring.store.DataStore; 021 022 import java.util.Map; 023 import java.util.Timer; 024 import java.util.TimerTask; 025 import java.util.concurrent.ConcurrentHashMap; 026 027 public final class DefaultGaugeManager implements GaugeManager { 028 private final Map<Role, Timer> timers = new ConcurrentHashMap<Role, Timer>(); 029 private final DataStore store; 030 031 public DefaultGaugeManager(final DataStore dataStore) { 032 store = dataStore; 033 } 034 035 @Override 036 public void stop() { 037 for (final Timer timer : timers.values()) { 038 timer.cancel(); 039 } 040 timers.clear(); 041 } 042 043 @Override 044 public void stopGauge(final Role role) { 045 final Timer timer = timers.remove(role); 046 if (timer != null) { 047 timer.cancel(); 048 } 049 } 050 051 @Override 052 public void addGauge(final Gauge gauge) { 053 final Role role = gauge.role(); 054 055 this.store.createOrNoopGauge(role); 056 057 final Timer timer = new Timer("gauge-" + role.getName() + "-timer", true); 058 timers.put(role, timer); 059 timer.scheduleAtFixedRate(new GaugeTask(store, gauge), 0, gauge.period()); 060 } 061 062 private static class GaugeTask extends TimerTask { 063 private final Gauge gauge; 064 private final DataStore store; 065 066 public GaugeTask(final DataStore store, final Gauge gauge) { 067 this.store = store; 068 this.gauge = gauge; 069 } 070 071 @Override 072 public void run() { 073 store.addToGauge(gauge, System.currentTimeMillis(), gauge.value()); 074 } 075 } 076 }