如何在Java中实现并发循环代码(计数器)?

2022-09-03 16:43:22

我想在Java中实现一个循环计数器。每个请求上的计数器应递增(原子方式),达到上限时应滚动到 0。

实现此目的的最佳方法是什么,是否有任何现有的实现?


答案 1

在顶部实现这样的计数器很容易: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;
    }

}

答案 2

使用 Java 8

public class CyclicCounter {

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

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

    public long incrementAndGet() {
        return counter.accumulateAndGet(1, (index, inc) -> (++index >= maxVal ? 0 : index));
    }

}

推荐