AtomicLong

Comprehensive guide to working with AtomicLong.

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

Overview

AtomicLong is the equivalent class for long type in the java.util.concurrent.atomic package as is AtomicInteger for int type. The AtomicLong class represents a long value that can be updated atomically, i.e. the read-modify-write operation can be executed atomically upon an instance of AtomicLong. The class extends Number.

Like the AtomicInteger class the AtomicLong` makes for great counters, sequence numbers etc as it uses the compare-and-swap (CAS) instruction under the hood. The CAS instruction doesn’t penalize competing threads for access to shared data/state 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.

Performance

To demonstrate the performance of AtomicLong 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 AtomicLong counter and an ordinary long counter. The widget below outputs the results:

Create a free account to view this lesson.

Continue your learning journey with a 14-day free trial.

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