In Java, AtomicInteger
and AtomicReference
are classes from the java.util.concurrent.atomic
package that provide a way to work with integers and object references in a thread-safe manner. These classes are part of the Java Concurrency framework and are designed to handle scenarios where multiple threads need to read and modify shared variables without the use of explicit synchronization.
AtomicInteger
allows you to work with an integer value atomically. This means that you can perform operations such as incrementing, decrementing, or setting a new value in a way that guarantees that no other thread will interfere with those operations, thus preventing inconsistent states.
The AtomicReference
class provides similar functionality for object references. It allows you to store, retrieve, and update references atomically, which is useful in multithreaded applications where multiple threads may be accessing and modifying the same object.
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class AtomicExample {
public static void main(String[] args) {
// Using AtomicInteger
AtomicInteger atomicInt = new AtomicInteger(0);
System.out.println("Initial Value: " + atomicInt.get());
atomicInt.incrementAndGet(); // Atomic increment
System.out.println("After Increment: " + atomicInt.get());
// Using AtomicReference
AtomicReference atomicRef = new AtomicReference<>("Initial");
System.out.println("Initial Reference: " + atomicRef.get());
atomicRef.set("Updated"); // Atomic set
System.out.println("After Update: " + atomicRef.get());
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?