AtomicInteger的实际用法 [英] Practical uses for AtomicInteger
问题描述
我理解AtomicInteger和其他Atomic变量允许并发访问。 AtomicInteger code>:
-
作为原子计数器(
incrementAndGet()$ c $
-
作为支持 compare-and-swap 指令(
compareAndSet()
)来实现非阻塞算法。
下面是 Brian的非阻塞随机数生成器示例Göetz的Java并发实践:
public class AtomicPseudoRandom extends PseudoRandom {
private AtomicInteger seed;
AtomicPseudoRandom(int seed){
this.seed = new AtomicInteger(seed);
}
public int nextInt(int n){
while(true){
int s = seed.get();
int nextSeed = calculateNext(s);
if(seed.compareAndSet(s,nextSeed)){
int remainder = s%n;
return remaining> 0?余数:余数+ n;
}
}
}
...
}
b $ b可以看到,它基本上与
incrementAndGet()
几乎相同,但执行任意计算(calculateNext
I sort of understand that AtomicInteger and other Atomic variables allow concurrent accesses. In what cases is this class typically used though?
There are two main uses of AtomicInteger
:
As an atomic counter (
incrementAndGet()
, etc) that can be used by many threads concurrentlyAs a primitive that supports compare-and-swap instruction (
compareAndSet()
) to implement non-blocking algorithms.Here is an example of non-blocking random number generator from Brian Göetz's Java Concurrency In Practice:
public class AtomicPseudoRandom extends PseudoRandom { private AtomicInteger seed; AtomicPseudoRandom(int seed) { this.seed = new AtomicInteger(seed); } public int nextInt(int n) { while (true) { int s = seed.get(); int nextSeed = calculateNext(s); if (seed.compareAndSet(s, nextSeed)) { int remainder = s % n; return remainder > 0 ? remainder : remainder + n; } } } ... }
As you can see, it basically works almost the same way as
incrementAndGet()
, but performs arbitrary calculation (calculateNext()
) instead of increment (and processes the result before return).
这篇关于AtomicInteger的实际用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!