concurrent map writes

Go Programming Language

Severity: Moderate

What it means

The full message: fatal error: concurrent map writes. A read during a write gives fatal error: concurrent map read and map write.
Go's blog: maps are not safe for concurrent use. Reads and writes from several goroutines must go through some kind of synchronization.
From Go 1.6, the runtime detects this, best effort, and crashes the program. It's a fatal error, not a panic: the runtime dumps a stack trace and exits, so recover can't stop it.

Affected Models

  • Go programs at run time

How to Fix It

  1. Run the program or its tests with the race detector: go run -race, or go test -race. Go's 1.6 notes: it identifies the race more reliably, and gives more detail.

  2. Guard the map with a mutex. Go's blog uses a sync.RWMutex: RLock and RUnlock around reads, Lock and Unlock around writes.

    Every access needs the lock, reads included.

  3. A cache that's written once and read many times, or goroutines that each work on their own keys? sync.Map is made for those two cases. Go's docs say most other code should use a plain map with its own lock.