Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a concurrent circular ticker (counter) in Java?

I want to implement a circular counter in Java. The counter on each request should increment (atomically) and on reaching an upper limit should roll over to 0.

What would be the best way to implement this and are there any existing implementations?

like image 290
sheki Avatar asked Sep 27 '11 16:09

sheki


1 Answers

It is easy to implement such a counter atop AtomicInteger:

public class CyclicCounter {

    private final int maxVal;
    private final AtomicInteger ai = new AtomicInteger(0);

    public CyclicCounter(int maxVal) {
        this.maxVal = maxVal;
    }

    public int cyclicallyIncrementAndGet() {
        int curVal, newVal;
        do {
          curVal = this.ai.get();
          newVal = (curVal + 1) % this.maxVal;
        } while (!this.ai.compareAndSet(curVal, newVal));
        return newVal;
    }

}
like image 65
NPE Avatar answered Sep 27 '22 16:09

NPE