1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ehcache.util.counter;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import net.sf.ehcache.util.FailSafeTimer;
23 import net.sf.ehcache.util.counter.sampled.SampledCounter;
24 import net.sf.ehcache.util.counter.sampled.SampledCounterImpl;
25
26 /***
27 * An implementation of a {@link CounterManager}.
28 *
29 * @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
30 * @since 1.7
31 *
32 */
33 public class CounterManagerImpl implements CounterManager {
34
35 private FailSafeTimer timer;
36 private boolean shutdown;
37 private List<Counter> counters = new ArrayList<Counter>();
38
39 /***
40 * Constructor that accepts a timer that will be used for scheduling sampled
41 * counter if any is created
42 */
43 public CounterManagerImpl(FailSafeTimer timer) {
44 if (timer == null) {
45 throw new IllegalArgumentException("Timer cannot be null");
46 }
47 this.timer = timer;
48 }
49
50 /***
51 * {@inheritDoc}
52 */
53 public synchronized void shutdown() {
54 if (shutdown) {
55 return;
56 }
57 try {
58
59
60 for (Counter counter : counters) {
61 if (counter instanceof SampledCounter) {
62 ((SampledCounter) counter).shutdown();
63 }
64 }
65 } finally {
66 shutdown = true;
67 }
68 }
69
70 /***
71 * {@inheritDoc}
72 */
73 public synchronized Counter createCounter(CounterConfig config) {
74 if (shutdown) {
75 throw new IllegalStateException("counter manager is shutdown");
76 }
77 if (config == null) {
78 throw new NullPointerException("config cannot be null");
79 }
80 Counter counter = config.createCounter();
81 if (counter instanceof SampledCounterImpl) {
82 SampledCounterImpl sampledCounter = (SampledCounterImpl) counter;
83 timer.schedule(sampledCounter.getTimerTask(), sampledCounter.getIntervalMillis(), sampledCounter.getIntervalMillis());
84 }
85 counters.add(counter);
86 return counter;
87 }
88
89 /***
90 * {@inheritDoc}
91 */
92 public void shutdownCounter(Counter counter) {
93 if (counter instanceof SampledCounter) {
94 SampledCounter sc = (SampledCounter) counter;
95 sc.shutdown();
96 }
97 }
98
99 }