The AtomicInteger class in Java provides a thread-safe way to perform operations on an integer value without the need for explicit synchronization. It is part of the java.util.concurrent package and is commonly used in multi-threaded applications where concurrent updates to an integer value may occur.
The AtomicInteger class provides methods such as get(), set(), getAndSet(), incrementAndGet(), decrementAndGet(), and compareAndSet(). These methods allow for safe manipulation of the integer value.
Here is an example code demonstrating how to use the AtomicInteger class:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private AtomicInteger count = new AtomicInteger(0);
public int getCount() {
return count.get();
}
public void incrementCount() {
count.incrementAndGet();
}
public void decrementCount() {
count.decrementAndGet();
}
public void resetCount() {
count.set(0);
}
}
In this example, we create a simple AtomicCounter class that uses an AtomicInteger to maintain an integer count. The incrementCount() and decrementCount() methods use the incrementAndGet() and decrementAndGet() methods of the AtomicInteger class to atomically increment or decrement the count.
The resetCount() method uses the set() method of the AtomicInteger class to reset the count to zero.
The get() method of the AtomicInteger class can be used to retrieve the current value of the integer, and the compareAndSet() method can be used to atomically set the value of the integer to a new value if and only if the current value matches a specified value.
Overall, the AtomicInteger class is a useful tool for performing thread-safe operations on an integer value without the need for explicit synchronization. It can help to avoid race conditions and other concurrency issues that can arise in multi-threaded applications.