Junior — Middle
Can you explain what the AtomicInteger class in Java is and why it is needed?
sobes.tech AI
Answer from AI
The AtomicInteger class in Java represents an integer variable whose operations are atomic, meaning indivisible and thread-safe without using synchronization.
Why is AtomicInteger needed:
- In multithreaded applications, for safely changing the value of a counter or other integer state without locks.
- It provides operations such as incrementAndGet(), decrementAndGet(), compareAndSet(), which are performed atomically.
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() without the risk of a race condition.