AtomicReferenceatomicInt = new AtomicReference<>(10); int expectedValue = 10; int newValue = 20; boolean isSuccess = atomicInt.compareAndSet(expectedValue, newValue); if (isSuccess) { System.out.println("Atomic Integer updated successfully"); } else { System.out.println("Failed to update Atomic Integer"); }
public class User { private final AtomicReferenceThis example shows how we can use an AtomicReference to implement a thread-safe User class. In this case, we use an AtomicReference to store the user's name, which can be updated using the setName() method. The getName() method returns the current value of the name reference. Since the AtomicReference provides thread-safe access to the value, we don't need to worry about race conditions or other synchronization issues.name = new AtomicReference<>(); public void setName(String newName) { name.set(newName); } public String getName() { return name.get(); } }