The java.util.concurrent.atomic package library contains the AtomicReference class which provides a way to store a reference to an object in a way that can be updated atomically. This means that multiple threads can access and modify the reference without causing concurrency issues or unexpected results.
Example 1: Simple AtomicReference usage
In this example, we create an AtomicReference object containing a string, and then update the reference with a new string.
AtomicReference atomicString = new AtomicReference<>("Hello"); atomicString.set("World"); System.out.println(atomicString.get()); // Output: World
Example 2: AtomicReference with compare-and-set behavior
In this example, we use the compareAndSet() method to atomically update an AtomicReference object only if the current value matches a certain criteria.
In this example, the compareAndSet() method updates the atomicInt reference to 10 only if its current value is 5. In this case, the update is successful, and the method returns true.
Overall, AtomicReference is a useful tool for handling concurrent updates to shared objects. It can be used in a wide range of scenarios, from thread-safe counters to managing shared state in a multi-threaded application.
Java AtomicReference - 30 examples found. These are the top rated real world Java examples of java.util.concurrent.atomic.AtomicReference extracted from open source projects. You can rate examples to help us improve the quality of examples.