AtomicInteger in Concurrent Programming
AtomicInteger is a Java class that enables concurrent access to an underlying integer value. Understanding the practical applications of AtomicInteger is crucial for optimizing concurrency in multi-threaded environments.
Typical Use Cases
AtomicInteger serves two primary purposes:
Example of Compare-and-Swap
Brian Göetz's "Java Concurrency In Practice" provides an example of using AtomicInteger for non-blocking random number generation:
public class AtomicPseudoRandom extends PseudoRandom { private AtomicInteger seed; ... public int nextInt(int n) { while (true) { int s = seed.get(); int nextSeed = calculateNext(s); if (seed.compareAndSet(s, nextSeed)) { ... } } } }
In this example, the seed value is atomically updated using compare-and-swap. The calculation to obtain the next seed is performed without blocking, ensuring that multiple threads can generate random numbers concurrently.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3