2 * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.bgp.rib.impl.stats;
10 import com.google.common.base.Preconditions;
11 import java.util.concurrent.atomic.AtomicLong;
12 import javax.annotation.Nonnull;
13 import javax.annotation.concurrent.ThreadSafe;
14 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.ZeroBasedCounter32;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
22 public class UnsignedInt32Counter {
23 private static final Logger LOG = LoggerFactory.getLogger(UnsignedInt32Counter.class);
24 private static final long MAX_VALUE = 4294967295L;
26 private final String counterName;
27 private final AtomicLong count = new AtomicLong();
29 public UnsignedInt32Counter(@Nonnull final String counterName) {
30 this.counterName = Preconditions.checkNotNull(counterName);
33 private static long safetyCheck(final long value) {
34 return Math.min(Math.max(0L, value), MAX_VALUE);
37 public long increaseCount(final long change) {
42 Preconditions.checkArgument(change > 0, "Count number %s must be a positive number.", change);
43 result = this.count.addAndGet(change);
44 LOG.debug("Counter [{}] is increased by {}. Current count: {}", this.counterName, change, result);
45 if (result > MAX_VALUE) {
46 LOG.warn("Counter [{}] has exceeded the max allowed value {}. Counter's current value {} is invalid.", this.counterName, MAX_VALUE, result);
52 public long increaseCount() {
53 return this.increaseCount(1);
56 public long decreaseCount(final long change) {
61 Preconditions.checkArgument(change > 0, "Count number %s must be a positive number.", change);
62 result = this.count.addAndGet(-change);
63 LOG.debug("Counter [{}] is decreased by {}. Current count: {}", this.counterName, change, result);
65 // In most case, we do not want the BGP session get into trouble due to an ERROR in counter
66 // so here we print ERROR log instead of throwing out exception
67 LOG.warn("Counter {} must not be less than 0. Counter's current value {} is invalid.", this.counterName, result);
73 public long decreaseCount() {
74 return this.decreaseCount(1);
77 public long getCount() {
78 return this.count.get();
81 public void setCount(final long count) {
82 final long result = getCount();
83 if (count != result) {
84 LOG.debug("Value of counter [{}] changes to {} (previous value is {})", this.counterName, count, result);
85 this.count.set(count);
89 public void resetCount() {
90 LOG.debug("Value of counter [{}] is reset to 0.", this.counterName);
94 public ZeroBasedCounter32 getCountAsZeroBasedCounter32() {
95 return new ZeroBasedCounter32(safetyCheck(getCount()));