Awesome Reviewers

Reviewer · Concurrency

Simplify and document synchronization

Favor the simplest correct synchronization primitive for the job, and make the concurrency contract of each type explicit in its documentation. - Prefer standard-library idioms over hand-rolled state for one-time or idempotent operations. Use `sync.Once`/`sync.OnceValue`/`sync.OnceValues` for lazy initialization and for close/shutdown paths that must run...

Instruction

Favor the simplest correct synchronization primitive for the job, and make the concurrency contract of each type explicit in its documentation.

  • Prefer standard-library idioms over hand-rolled state for one-time or idempotent operations. Use sync.Once/sync.OnceValue/sync.OnceValues for lazy initialization and for close/shutdown paths that must run exactly once, instead of ad-hoc booleans or multiple interacting mutexes/atomics. For example, replace:
    func (l *logStream) Close() error {
        l.closed.Store(true)
        l.messages.Close()
        close(l.closedCh) // panics if called twice
        return nil
    }
    

    with:

    func (l *logStream) Close() error {
        l.closeOnce.Do(func() {
            close(l.closedCh)
            l.messages.Close()
        })
        return nil
    }
    

    Before introducing extra mutexes, pointer indirection, or atomic flags to coordinate competing operations (e.g. a “write” lock plus an “update” lock plus a race flag), check whether a channel-as-semaphore, sync.Once, or restructuring to avoid the second code path entirely gives the same guarantees with less code and fewer races.

  • Document, in godoc on the type/method, what synchronization is required and who is responsible for it: whether a method expects the caller to already hold a lock, whether it acquires its own lock internally, and which fields are immutable after construction (and therefore safe to read without a lock) versus which are mutable and protected by which mutex. Avoid method names/signatures that look safe for concurrent use but silently require external locking (e.g. a SetX method that mutates state without locking, called both with and without a lock held elsewhere); either make the method self-contained and safe, or inline/open-code the mutation at the call site so the locking requirement is obvious.

  • When refactoring or adding concurrency, preserve correct ordering between acquiring a lock/semaphore and mutating or reading shared state: don’t mutate a shared slice/map from a goroutine while it is still being iterated elsewhere, acquire a per-resource lock before incrementing a shared refcount (and before releasing it on decrement) rather than after, and bound goroutine creation by acquiring the limiting semaphore immediately before spawning the goroutine rather than inside it. If a pre-existing race is discovered incidental to other work, it’s fine to flag it and defer the fix to a follow-up, but it must not be made worse by the change in hand.