Video in progress
When is it worth writing a lock-free data structure yourself? Explain with the Michael-Scott queue as an example.
Almost never in business code: in the JDK, ConcurrentLinkedQueue is built on exactly the Michael-Scott algorithm. Writing your own is worth it when the profiler shows clear contention, the existing structures don't fit, and you have time to verify with jcstress.
📖 Answer
Lock-free means that even if one thread stalls, the system as a whole keeps moving forward. It doesn't mean "faster" than a lock: CAS retries, heavy allocation and complexity all have a cost.
The idea of the Michael-Scott queue: head and tail are atomic references, with a "sentinel" node at the start.
boolean offer(E item) {
Node<E> node = new Node<>(item);
while (true) {
Node<E> last = tail.get();
Node<E> next = last.next.get();
if (last == tail.get()) { // is tail still current
if (next == null) {
if (last.next.compareAndSet(null, node)) {
tail.compareAndSet(last, node); // fine even if this fails
return true;
}
} else {
tail.compareAndSet(last, next); // we "help" another thread
}
}
}
}
The key trick is helping: if tail is lagging behind, any thread moves it forward. So even though the two-step insert (link + move tail) isn't atomic, the structure stays consistent.
What's hard:
- every intermediate state can be seen by another thread, so you have to think through all of them;
- reclaiming memory: in C++ you need hazard pointers, while in Java the GC solves it (which is why lock-free is much easier in Java);
- testing: an ordinary unit test almost never finds the bug.
My checklist before writing my own structure:
- Is lock contention really the bottleneck in JFR/async-profiler?
- Is there a suitable structure in the JDK or in JCTools, Agrona or the Disruptor? (SPSC/MPSC queues are usually ready-made there.)
- Can the problem be solved with architecture, for example by removing shared state through partitioning?
If all three answers are "no", then write it, with jcstress tests, a JMH benchmark and a review by at least two people.
Sign up to mark studied questions and save your progress.