An atomic operation is indivisible - it either completes entirely or not at all. No other thread can observe it in a partial state.
The All-or-Nothing Principle
Think of atomicity like a light switch. It is either on or off. You cannot observe it halfway between positions. There is no flickering state where another person might see something inconsistent.
Atomic vs Non-Atomic Operation
Why Atomicity Matters
counter++ looks like one operation but compiles to three: load value, add one, store result. Another thread can sneak in between any of these steps.
Torn reads/writes: On some architectures, even a single 64-bit write might not be atomic. Half the value could be written before context switch, leaving garbage.
What Is Naturally Atomic
On most modern CPUs, aligned reads and writes of machine-word-sized values are atomic. But naturally atomic is not enough - you also need proper memory ordering (a separate topic).
Key Point: Do not assume operations are atomic. Use explicit atomic types or synchronization to guarantee it.
💡 Key Takeaways
✓Atomic operations complete entirely or not at all. No thread can see an intermediate state.
✓counter++ is NOT atomic in most languages. It is three operations: load, add, store.
✓Hardware provides atomic instructions like compare and swap (CAS) that are truly indivisible.
✓Atomicity prevents race conditions by ensuring operations cannot interleave at critical points.
✓Languages provide atomic types (AtomicInteger in Java, atomic in C++, sync/atomic in Go) for thread safe operations.
📌 Examples
1Non atomic: x = x + 1 can lose updates when two threads run simultaneously.
2Atomic: atomicInteger.incrementAndGet() is guaranteed to increment correctly even with concurrent access.