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.ratestatistics;
18
19 import java.util.concurrent.TimeUnit;
20
21 /***
22 * A lightweight non-thread-safe rate statistic implementation.
23 *
24 * @author Chris Dennis
25 */
26 public class UnlockedRateStatistic extends AbstractRateStatistic {
27
28 private volatile long count;
29 private volatile long rateSampleTime = System.nanoTime();
30 private volatile float rateSample = Float.NaN;
31
32 private volatile long sampleRateMask;
33 private volatile long previousSample;
34
35 /***
36 * Create an UnlockedRateStatistic instance with the given average period.
37 *
38 * @param averagePeriod average period
39 * @param unit period time unit
40 */
41 public UnlockedRateStatistic(long averagePeriod, TimeUnit unit) {
42 super(averagePeriod, unit);
43 }
44
45 /***
46 * {@inheritDoc}
47 */
48 public void event() {
49 long value = ++count;
50 if ((value & sampleRateMask) == 0) {
51 long now = System.nanoTime();
52 long previous = rateSampleTime;
53 rateSampleTime = now;
54 float nowRate = ((float) (value - previousSample) / (now - previous));
55 previousSample = value;
56 rateSample = iterateMovingAverage(nowRate, now, rateSample, previous);
57 long suggestedSampleRateMask = Long.highestOneBit(Math.max(1L, (long) (getRateAveragePeriod() * rateSample))) - 1;
58 if (suggestedSampleRateMask != sampleRateMask) {
59 sampleRateMask = suggestedSampleRateMask;
60 }
61 }
62 }
63
64 /***
65 * {@inheritDoc}
66 */
67 public long getCount() {
68 return count;
69 }
70
71 /***
72 * {@inheritDoc}
73 */
74 public float getRate() {
75 long then = rateSampleTime;
76 long lastSample = previousSample;
77 float thenAverage = rateSample;
78 long now = System.nanoTime();
79 float nowValue = ((float) (count - lastSample)) / (now - then);
80 final float rate = iterateMovingAverage(nowValue, now, thenAverage, then) * TimeUnit.SECONDS.toNanos(1);
81 if (Float.isNaN(rate)) {
82 if (Float.isNaN(thenAverage)) {
83 return 0f;
84 } else {
85 return thenAverage;
86 }
87 } else {
88 return rate;
89 }
90 }
91 }