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:
AtomicInteger
As an atomic counter (incrementAndGet(), etc) that can be used by many threads concurrently
incrementAndGet()
As a primitive that supports compare-and-swap instruction (compareAndSet()) to implement non-blocking algorithms.
compareAndSet()
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).
calculateNext()
1.4m articles
1.4m replys
5 comments
57.0k users