Merge branch 'master' of ../controller
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / SynchronizedDurationStatsTracker.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util;
9
10 import com.google.common.primitives.UnsignedLong;
11
12 /**
13  * Non-concurrent implementation, useful for non-contended cases.
14  */
15 final class SynchronizedDurationStatsTracker extends DurationStatisticsTracker {
16     private static final long NOT_SET = -1;
17
18     // Hot fields in the order in which they are accessed
19     private long durationSum = 0;
20     private long durationCount = 0;
21     private long shortestDuration = NOT_SET;
22     private long longestDuration = NOT_SET;
23
24     // Cold fields, longest has a higher chance of being accessed
25     private long longestTimestamp;
26     private long shortestTimestamp;
27
28     SynchronizedDurationStatsTracker() {
29         // Hidden on purpose
30     }
31
32     @Override
33     public synchronized void addDuration(final long duration) {
34         durationSum += duration;
35         durationCount++;
36
37         if (duration < shortestDuration || shortestDuration == NOT_SET) {
38             shortestDuration = duration;
39             shortestTimestamp = System.currentTimeMillis();
40         }
41         if (duration > longestDuration) {
42             longestDuration = duration;
43             longestTimestamp = System.currentTimeMillis();
44         }
45     }
46
47     @Override
48     public synchronized double getAverageDuration() {
49         return durationCount == 0 ? 0 : UnsignedLong.fromLongBits(durationSum).doubleValue() / durationCount;
50     }
51
52     @Override
53     public synchronized long getTotalDurations() {
54         return durationCount;
55     }
56
57     @Override
58     public synchronized void reset() {
59         durationSum = 0;
60         durationCount = 0;
61         longestDuration = NOT_SET;
62         shortestDuration = NOT_SET;
63     }
64
65     @Override
66     protected synchronized DurationWithTime getShortest() {
67         return shortestDuration == NOT_SET ? null : new DurationWithTime(shortestDuration, shortestTimestamp);
68     }
69
70     @Override
71     protected synchronized DurationWithTime getLongest() {
72         return longestDuration == NOT_SET ? null : new DurationWithTime(longestDuration, longestTimestamp);
73     }
74 }