educative.io

Performance of long vs AtomicLong

By running the example in this chapter, I got result like:

Time taken by atomic long counter 156 milliseconds.
Time taken by long counter 237 milliseconds.

It is kinda counter intuitive for me, that AtomicLong has a better performance than Long.
Can you explain why?
And if that is true, then in theory, any Long should be replaced by AtomicLong because the latter is faster and thread-safe, which feels wrong.


Course: Java Multithreading for Senior Engineering Interviews - Learn Interactively
Lesson: AtomicLong - Java Multithreading for Senior Engineering Interviews

Hello @Zihao_Wang The performance difference between AtomicLong and a regular long counter depends on their implementation and use cases.

AtomicLong uses compare-and-swap (CAS) instructions, that allows atomic updates without the need for locks. On the other hand, a regular long counter requires explicit synchronization using locks or other mechanisms to ensure thread safety.

And AtomicLong may not always be faster than a regular long counter in cases when there are many threads fighting over the counter. In those cases, the CAS operations used by AtomicLong might have to try again and again, which can actually slow things down compared to using locks that pause threads and prevent contention. It’s also worth mentioning that AtomicLong takes more space than long because of the internal implementation.

Regarding your second question, Whether to replace a Long with an AtomicLong depends on your application’s requirements. If you need thread-safe atomic updates on long values with concurrent access and modifications, AtomicLong is beneficial. However, in single-threaded contexts or when thread safety isn’t necessary, using a regular long variable is more suitable and efficient.

1 Like