If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The AtomicInteger class represents an integer value that can be updated atomically, i.e. the read-modify-write operation can be executed atomically upon an instance of AtomicInteger. The class extends Number.

AtomicInteger makes for great counters as it uses the compare-and-swap (CAS) instruction under the hood which doesn’t penalize threads competing for access to the same data with suspension as locks do In general, suspension and resumption of threads involves significant overhead and under low to moderate contention non-blocking algorithms that use CAS outperform lock-based alternatives.

You can find more details on non-blocking synchronization and atomics here.

Performance

To demonstrate the performance of AtomicInteger we can construct a crude test, where a counter is incremented a million times by ten threads to reach a total of ten million. We’ll time the run for an AtomicInteger counter and an ordinary int counter. The widget below outputs the results:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy