我正在使用JMH来测试我的项目的一些功能。当我尝试在AtomicInteger中使用它的@GroupThreads时,我无法重置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
}
}发布于 2016-09-27 18:13:39
这是一种内在的竞赛。您可能永远不会在CAS(10, -1)中观察到10 --当多个线程在10上递增运行时--因此会错过重置操作。如果你想正确地同步计数器模N,我建议详细说明这个未经测试的草图:
int countUp() {
int cur, next;
do {
cur = counter.get();
next = cur < N ? (cur + 1) : 0;
} while (!counter.compareAndSet(cur, next));
return next;
}...or,在Java8中:
int countUp() {
return counter.updateAndGet(v -> (v < N) ? (v + 1) : 0);
}https://stackoverflow.com/questions/39703237
复制相似问题