c5f187293b9e843a239f24dd0981aba7b9574ece
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / statistics / Counter.java
1 /*\r
2  * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
3  *\r
4  * This program and the accompanying materials are made available under the\r
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
6  * and is available at http://www.eclipse.org/legal/epl-v10.html\r
7  */\r
8 \r
9 package org.opendaylight.openflowjava.statistics;\r
10 \r
11 import java.util.concurrent.atomic.AtomicLong;\r
12 /**\r
13  * Counts statistics\r
14  * \r
15  * @author madamjak\r
16  */\r
17 public class Counter {\r
18 \r
19     private AtomicLong counterValue;\r
20     private AtomicLong counterLastReadValue;\r
21 \r
22     /**\r
23      * Default constructor\r
24      */\r
25     public Counter() {\r
26         counterValue = new AtomicLong(0L);\r
27         counterLastReadValue = new AtomicLong(0L);\r
28     }\r
29 \r
30     /**\r
31      * Increment current counter value\r
32      */\r
33     public void incrementCounter(){\r
34         counterValue.incrementAndGet();\r
35     }\r
36 \r
37     /**\r
38      * return the last read value of counter. This value can be set during the reading of current counter value, \r
39      *      for detail see method getCounterValue(boolean modifyLastReadValue).\r
40      * @return the counterLastReadValue\r
41      */\r
42     public long getCounterLastReadValue() {\r
43         return counterLastReadValue.get();\r
44     }\r
45 \r
46     /**\r
47      * get current value of counter and rewrite CounterLastReadValue by current value\r
48      * @return  the current value of counter\r
49      */\r
50     public long getCounterValue() {\r
51         return getCounterValue(true);\r
52     }\r
53 \r
54     /**\r
55      * get current counter value\r
56      * @param modifyLastReadValue\r
57      *      true - CounterLastReadValue will be rewritten by current CounterValue\r
58      *      false - no change CounterLastReadValue\r
59      * @return the current value of counter\r
60      */\r
61     public long getCounterValue(boolean modifyLastReadValue) {\r
62         if(modifyLastReadValue){\r
63             counterLastReadValue.set(counterValue.get());\r
64         }\r
65         return counterValue.get();\r
66     }\r
67 \r
68     /**\r
69      * set current counter value and CounterLastReadValue to 0 (zero)\r
70      */\r
71     public void reset(){\r
72         counterValue.set(0l);\r
73         counterLastReadValue.set(0l);\r
74     }\r
75 \r
76     /**\r
77      * @return last and current count for specified statistic\r
78      */\r
79     public String getStat() {\r
80         long cntPrevVal = getCounterLastReadValue();\r
81         long cntCurValue = getCounterValue();\r
82         return String.format("+%d | %d",cntCurValue-cntPrevVal,cntCurValue);\r
83     }\r
84 }