Video in progress
What is better about AtomicInteger than a plain int?
AtomicInteger performs read-modify-write operations atomically through CAS, without locks. So even when many threads increment it, not a single value is lost.
📖 Answer
private final AtomicInteger requests = new AtomicInteger();
void onRequest() {
requests.incrementAndGet(); // thread-safe
}
Inside, compare-and-swap (CAS) is at work: "if the value is still 5, make it 6". If another thread changed it first, the operation fails and retries. The thread is never blocked.
Useful methods:
incrementAndGet(),getAndAdd(n);compareAndSet(expected, newValue);updateAndGet(x -> Math.max(x, value)), for more complex updates (the lambda may be called again, so keep it free of side effects).
The limitation: atomicity covers only a single variable. If you need to change two atomic variables "together" (say, min and max), this isn't enough, and you need a lock or a single immutable object stored in an AtomicReference.
Sign up to mark studied questions and save your progress.