Sobes.tech
Senior

What is AtomicInteger, what is it used for, and what are its advantages?

sobes.tech AI

Answer from AI

AtomicInteger is a class from the java.util.concurrent.atomic package that provides atomic operations on an integer value. It is used for safely modifying numeric values in a multithreaded environment without the need to use synchronization via synchronized or locks.

The advantage of AtomicInteger is that it offers high performance and safety in concurrent access by using low-level atomic CPU instructions.

Example usage:

import java.util.concurrent.atomic.AtomicInteger;

public class Counter {
    private AtomicInteger count = new AtomicInteger(0);

    public void increment() {
        count.incrementAndGet(); // atomic increment by 1
    }

    public int getCount() {
        return count.get();
    }
}

In this example, the increment() method is safe to be called from multiple threads simultaneously without the risk of a race condition.