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.values;
19
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.concurrent.CopyOnWriteArrayList;
23
24 import org.apache.commons.monitoring.Composite;
25 import org.apache.commons.monitoring.Counter;
26 import org.apache.commons.monitoring.Gauge;
27 import org.apache.commons.monitoring.Role;
28 import org.apache.commons.monitoring.Unit;
29
30 /**
31 * A composite implementation of {@link Counter} that delegates to a primary
32 * implementation and maintains a collection of secondary counters.
33 * <p>
34 * Typical use is to create monitoring graphs : On regular time intervals, a
35 * new secondary counter is registered to computes stats for the current period,
36 * and then removed.
37 *
38 * @author <a href="mailto:nicolas@apache.org">Nicolas De Loof</a>
39 */
40 public class CompositeCounter extends ThreadSafeCounter implements Composite<Counter>
41 {
42 private Collection<Counter> secondary;
43
44 public Collection<Counter> getSecondary()
45 {
46 return Collections.unmodifiableCollection( secondary );
47 }
48
49 public CompositeCounter( Role<Counter> role )
50 {
51 super( role );
52 this.secondary = new CopyOnWriteArrayList<Counter>();
53 }
54
55 public Counter createSecondary()
56 {
57 Counter counter = new ThreadSafeCounter( getRole() );
58 secondary.add( counter );
59 return counter;
60 }
61
62 public void removeSecondary( Counter counter )
63 {
64 secondary.remove( counter );
65 }
66
67 public void add( long delta, Unit unit )
68 {
69 super.add( delta, unit );
70 for ( Counter counter : secondary )
71 {
72 counter.add( delta, unit );
73 }
74 }
75
76 public void set( long l, Unit unit )
77 {
78 super.set( l, unit );
79 for ( Counter counter : secondary )
80 {
81 counter.set( l, unit );
82 }
83 }
84
85 }