Lock-Free Programming
Locks are simple and correct, but they have one uncomfortable property: while a thread holds a lock, everyone else who needs it waits. If the holder gets paused by the operating system in the middle of its critical section (its time slice ran out, it hit a page fault), every waiting thread is stuck behind a thread that isn't even running. Under heavy load, threads pile up in a convoy behind each lock, and a deadlock freezes them for good.
Lock-free programming avoids that by never making a thread wait for another. Instead of "take the lock, then change the data," a thread prepares its change, then applies it with a single hardware instruction that succeeds only if nobody else changed the data in the meantime. If someone did, it simply tries again. This post builds from that one instruction, compare-and-swap, to a lock-free counter, stack and queue, explains the famous ABA problem, and ends with when you should not bother.
💡 Why this matters in an interview: you will almost never be asked to write a lock-free queue from scratch. You will be asked how
AtomicIntegerorConcurrentHashMapcan be thread safe without locks, what a CAS loop is, and what ABA means. Knowing the ideas, and knowing when a lock is better, is what earns credit.
Blocking and Non-Blocking
Start with what "lock-free" promises, because it is more precise than "no locks in the code."
- Blocking: a thread can be stopped indefinitely by another thread. Any lock-based code is blocking: if the lock holder is paused, the others wait.
- Lock-free: at any moment, at least one thread makes progress. A single thread can lose the race and retry many times, but the system as a whole never stalls, and pausing one thread never stops the others.
- Wait-free: every thread finishes its operation in a bounded number of its own steps, no matter what the others do. This is the strongest guarantee and the hardest to build.
Both lock-free and wait-free are non-blocking. Deadlock is impossible in non-blocking code, because no thread ever holds something another thread waits for. Starvation of one unlucky thread is still possible in lock-free code (it can keep losing the retry race), which is the gap wait-free code closes.