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.io.Serializable;
20 import java.util.concurrent.atomic.AtomicLong;
21
22 /***
23 * A simple counter implementation
24 *
25 * @author <a href="mailto:asanoujam@terracottatech.com">Abhishek Sanoujam</a>
26 * @since 1.7
27 *
28 */
29 public class CounterImpl implements Counter, Serializable {
30 private AtomicLong value;
31
32 /***
33 * Default Constructor
34 */
35 public CounterImpl() {
36 this(0L);
37 }
38
39 /***
40 * Constructor with initial value
41 *
42 * @param initialValue
43 */
44 public CounterImpl(long initialValue) {
45 this.value = new AtomicLong(initialValue);
46 }
47
48 /***
49 * {@inheritDoc}
50 */
51 public long increment() {
52 return value.incrementAndGet();
53 }
54
55 /***
56 * {@inheritDoc}
57 */
58 public long decrement() {
59 return value.decrementAndGet();
60 }
61
62 /***
63 * {@inheritDoc}
64 */
65 public long getAndSet(long newValue) {
66 return value.getAndSet(newValue);
67 }
68
69 /***
70 * {@inheritDoc}
71 */
72 public long getValue() {
73 return value.get();
74 }
75
76 /***
77 * {@inheritDoc}
78 */
79 public long increment(long amount) {
80 return value.addAndGet(amount);
81 }
82
83 /***
84 * {@inheritDoc}
85 */
86 public long decrement(long amount) {
87 return value.addAndGet(amount * -1);
88 }
89
90 /***
91 * {@inheritDoc}
92 */
93 public void setValue(long newValue) {
94 value.set(newValue);
95 }
96
97 }