Section 12
Sync Primitives
Go's sync package provides the low-level primitives for protecting shared state when channels are not the right tool. In a comms engine, these are everywhere.
☕Java has
synchronized, ReentrantLock, CountDownLatch, AtomicInteger. Go has simpler equivalents with slightly different names and explicit lock/unlock rather than block-scoped locking.sync.Mutex — exclusive lock
☕ Java — synchronized method or ReentrantLock
◎ Go — sync.Mutex
Why Go does thisThe
defer e.mu.Unlock() pattern guarantees the lock is released no matter what happens — early returns, panics, any code path. Forgetting an Unlock causes a deadlock that never recovers. Defer makes forgetting impossible.sync.RWMutex — multiple readers, exclusive writer
RWMutex — optimise for read-heavy workloads
sync.WaitGroup — coordinate goroutine completion
WaitGroup — wait for a batch of goroutines
sync.Once — run exactly once, ever
sync.Once — singleton initialisation
sync/atomic — lock-free integer operations
atomic — faster than mutex for counters
sync.Map — concurrent-safe map
sync.Map — for specific access patterns