KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > stats > counter > CounterImpl


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.stats.counter;
5
6 /**
7  * A simple counter implementation
8  */

9 public class CounterImpl implements Counter {
10   private long value;
11   private long min;
12   private long max;
13
14   public CounterImpl() {
15     this(0L);
16   }
17
18   public CounterImpl(long initialValue) {
19     this.value = initialValue;
20     this.min = initialValue;
21     this.max = initialValue;
22   }
23
24   public synchronized long increment() {
25     final long newValue = ++this.value;
26     setValue(newValue);
27     return newValue;
28   }
29
30   public synchronized long decrement() {
31     final long newValue = --this.value;
32     setValue(newValue);
33     return newValue;
34   }
35
36   public synchronized long getAndSet(long newValue) {
37     final long previousValue = this.value;
38     setValue(newValue);
39     return previousValue;
40   }
41
42   public synchronized long getValue() {
43     return this.value;
44   }
45
46   public synchronized long getMaxValue() {
47     return this.max;
48   }
49
50   public synchronized long getMinValue() {
51     return this.min;
52   }
53
54   public synchronized long increment(long amount) {
55     final long newValue = this.value += amount;
56     setValue(newValue);
57     return newValue;
58   }
59
60   public synchronized long decrement(long amount) {
61     final long newValue = this.value -= amount;
62     setValue(newValue);
63     return newValue;
64   }
65
66   public synchronized void setValue(long newValue) {
67     if (newValue > this.max) {
68       this.max = newValue;
69     }
70
71     if (newValue < this.min) {
72       this.min = newValue;
73     }
74
75     this.value = newValue;
76   }
77
78 }
79
Popular Tags