You’ve successfully removed a node from a lock-free data structure. Can you safely free its memory?
Not necessarily.
Imagine two threads accessing a lock-free linked list.
- Thread A reads a pointer to node X.
- Thread B uses an atomic Compare-And-Swap (CAS) operation to remove X from the list.
- The removal succeeds.
- Thread B frees X.
- Thread A resumes and dereferences its pointer.
You now have a Use-after-free bug.
The atomic operation worked exactly as intended.
The memory management did not.
CAS guarantees atomic pointer updates, not object lifetime safety.
This is where Epoch-Based Reclamation (EBR) comes in.
1. Separate logical removal from physical reclamation
Instead of freeing a removed object immediately, EBR delays reclamation until no active reader can still reference it.
The basic mechanism:
- Threads announce their participation in a global epoch before accessing shared objects.
- Removed objects are placed in a retired list.
- The global epoch advances as participating threads progress.
- Objects are reclaimed only after potentially referencing readers have exited their protected sections.
Rather than tracking every object reference, EBR tracks groups of readers through epochs.
This can significantly reduce synchronization overhead on the read path.
2. A real-world example: Rust’s crossbeam-epoch
A thread pins itself before accessing shared data:
let guard = epoch::pin();Once an object has been safely removed, its destruction can be deferred:
guard.defer_destroy(removed);The second operation requires the appropriate unsafe contract.
The object is no longer logically accessible through the data structure, but its memory remains available until reclamation is safe.
4. The engineering tradeoff
EBR offers low read-path overhead and efficient batched reclamation.
But long-running or stalled readers can delay reclamation.
Alternatives such as Hazard Pointers explicitly protect individual objects, introducing different synchronization costs and progress guarantees.
Avoid holding epoch guards across blocking I/O or long-running operations.
The key takeaway:
Removing an object and proving that nobody can still access it are two separate concurrency problems.