Junior — Middle
Explain the functioning principle of the AtomicInteger class in Java and how it ensures thread safety.
sobes.tech AI
Answer from AI
The AtomicInteger class in Java provides an integer value, operations on which are atomic, meaning they are executed completely or not at all, without interruption from other threads. This ensures safe state management in a multithreaded environment without explicit synchronization.
Main methods of AtomicInteger, such as incrementAndGet(), decrementAndGet(), compareAndSet(), use low-level atomic CPU instructions (e.g., CAS — compare-and-swap), which help avoid data races.
Example of usage:
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void increment() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
In this example, multiple threads can safely call increment(), and the value of count will be correctly incremented without additional locks.