Friday, February 3, 2023

AtomicInteger, AtomicLong, and AtomicReference

 

AtomicInteger, AtomicLong, and AtomicReference are classes in the java.util.concurrent.atomic package that provide a simple way to perform atomic operations on variables. Atomic operations are operations that are guaranteed to be atomic, even in the presence of multiple threads.

AtomicInteger, AtomicLong, and AtomicReference provide methods for performing common operations such as incrementing, decrementing, and exchanging values in an atomic manner. Here is an example of how you can use the AtomicInteger class:


import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerExample { public static void main(String[] args) { AtomicInteger atomicInt = new AtomicInteger(0); System.out.println("Value: " + atomicInt.get()); int result = atomicInt.incrementAndGet(); System.out.println("Result: " + result); result = atomicInt.addAndGet(10); System.out.println("Result: " + result); boolean updated = atomicInt.compareAndSet(11, 100); System.out.println("Success: " + updated); System.out.println("Value: " + atomicInt.get()); int expectedValue = atomicInt.get(); updated = atomicInt.compareAndSet(100, expectedValue + 1); System.out.println("Success: " + updated); System.out.println("Value: " + atomicInt.get()); } }

In this example, we create an instance of the AtomicInteger class with a value of 0. We then use the incrementAndGet method to increment the value of the atomic integer, and the addAndGet method to add 10 to the value of the atomic integer.

The compareAndSet method is used to compare the value of the atomic integer with a specified value, and if the values are equal, set the value of the atomic integer to a new value. In this example, the compareAndSet method is used to try to set the value of the atomic integer to 100. If the current value of the atomic integer is equal to 11, the value is updated, otherwise the update fails.

AtomicLong and AtomicReference work similarly to AtomicInteger, but they provide methods for performing atomic operations on long values and object references, respectively

No comments:

Post a Comment