Confinement
Confine mutable state to one owner and communicate with that owner instead of sharing state broadly.
Canonical guidance
- prefer ownership over shared mutation
- communicate with the owner rather than poking at its state
- transfer ownership deliberately when needed
Use when
- caches or aggregators with one logical owner
- event loops
- state machines with serialized updates
Avoid
- a “mostly owned” structure that many goroutines still mutate directly
- mixing channel requests with unsynchronized side access
- exporting internal mutable references casually
Preferred pattern
- one goroutine owns a map and serves reads or writes through requests
Anti-pattern
- a worker owns a queue but other goroutines also append to the backing slice directly
Explanation: This is tempting because the direct access is short, but it breaks the whole ownership story.
Why
- confinement removes entire classes of synchronization bugs
Related pages
Sources
- Concurrency is not parallelism - Rob Pike
- Advanced Go Concurrency Patterns - Sameer Ajmani