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
18 package org.apache.commons.monitoring.impl.monitors;
19
20 import org.apache.commons.monitoring.Counter;
21 import org.apache.commons.monitoring.Gauge;
22 import org.apache.commons.monitoring.Role;
23 import org.apache.commons.monitoring.impl.values.ThreadSafeCounter;
24 import org.apache.commons.monitoring.impl.values.ThreadSafeGauge;
25
26 /**
27 * implementation of the <code>Monitor</code> interface that creates StatValues on
28 * demand. The application can request for Counters/Gauges without having to
29 * handle instantiation of monitors with all required StatValues pre-registered.
30 *
31 * @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
32 */
33 public class CreateValuesOnDemandMonitor
34 extends ObservableMonitor
35 {
36
37 public CreateValuesOnDemandMonitor( Key key )
38 {
39 super( key );
40 }
41
42 /**
43 * Retrieve a Counter or create a new one for the role
44 */
45 @Override
46 public Counter getCounter( Role<Counter> role )
47 {
48 Counter counter = getValue( role );
49 if ( counter != null )
50 {
51 return counter;
52 }
53 counter = newCounterInstance( role );
54 Counter previous = register( counter );
55 return previous != null ? previous : counter;
56 }
57
58 /**
59 * Create a new Counter instance
60 */
61 protected Counter newCounterInstance( Role<Counter> role )
62 {
63 return new ThreadSafeCounter( role );
64 }
65
66 /**
67 * Retrieve a Gauge or create a new one for the role
68 */
69 @Override
70 public Gauge getGauge( Role<Gauge> role )
71 {
72 Gauge gauge = getValue( role );
73 if ( gauge != null )
74 {
75 return gauge;
76 }
77 gauge = newGaugeInstance( role );
78 Gauge previous = register( gauge );
79 return previous != null ? previous : gauge;
80 }
81
82 /**
83 * Create a new Gauge instance
84 */
85 protected Gauge newGaugeInstance( Role<Gauge> role )
86 {
87 return new ThreadSafeGauge( role );
88 }
89
90 }