1

我正在使用 JMH 来测试我的项目的一些功能。当我尝试将 @GroupThreads 与 AtomicInteger 一起使用时,我无法重置 AtomicInteger,它只会随着时间的推移而增加。我还尝试使用 if else 检查和重置 AtomicInteger 但不能。你能给我一些关于我的问题的建议吗?非常感谢。

class JMHSample_15_Asymmetric {

  private var counter: AtomicInteger = _

  @Setup
  def up() {
    counter = new AtomicInteger
  }

  @Benchmark
  @Group("g")
  @GroupThreads(3)
  def inc: Int = {
    counter.compareAndSet(10,-1)
    counter.incrementAndGet
  }
  @Benchmark
  @Group("g")
  @GroupThreads(1)
  def get: Int = {
    println("Counter --> "+ counter.get)
    counter.get
  }

}
4

1 回答 1

1

有一个内在的种族。您可能永远不会观察10CAS(10, -1)——当多个线程运行增量超过时10——因此错过了重置操作。如果您想正确同步计数器模 N,我建议您详细说明这个未经测试的草图:

int countUp() {
  int cur, next;
  do {
    cur = counter.get();
    next = cur < N ? (cur + 1) : 0;
  } while (!counter.compareAndSet(cur, next));
  return next;
}

...或者,在 Java 8 中:

int countUp() {
  return counter.updateAndGet(v -> (v < N) ? (v + 1) : 0);
}
于 2016-09-27T10:13:38.733 回答