Deduplicate Concurrent Writes With sync.Map LoadOrStore

Coordinate concurrent goroutines with sync.Map.LoadOrStore so only one winner initializes each shared key while peers receive the existing value.

GoResilience

Code

snippet
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var store sync.Map
	var winners, reused atomic.Int32
	var wg sync.WaitGroup

	keys := []string{"tenant:a", "tenant:b"}
	for worker := 1; worker <= 4; worker++ {
		for _, key := range keys {
			wg.Add(1)
			go func(id int, k string) {
				defer wg.Done()
				candidate := fmt.Sprintf("owner-worker-%d", id)
				actual, loaded := store.LoadOrStore(k, candidate)
				if !loaded {
					winners.Add(1)
				} else if actual != nil {
					reused.Add(1)
				}
			}(worker, key)
		}
	}
	wg.Wait()

	fmt.Printf("winners=%d reused=%d\n", winners.Load(), reused.Load())
	for _, key := range keys {
		val, ok := store.Load(key)
		fmt.Printf("key=%s found=%t winner=%v\n", key, ok, val)
	}
}

Implementation trace — Deduplicate Concurrent Writes With sync.Map LoadOrStore

Under the hood: the function main.

The file repeats itself only inside for worker := 1; worker <= 4; worker++. Work is dispatched on a goroutine. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Points of care

  • Uses strictly native APIs, eliminating external supply-chain audit concerns.

Using it

Key routine declaration reads as func main()

The run emits 2 labeled sections — winners=, key= — one per step.

Key statements

go func(id int, k string) {
	defer wg.Done()
	candidate := fmt.Sprintf("owner-worker-%d", id)
	actual, loaded := store.LoadOrStore(k, candidate)
	if !loaded {
		winners.Add(1)
	} else if actual != nil {
		reused.Add(1)
	}
}(worker, key)
for _, key := range keys {
	val, ok := store.Load(key)
	fmt.Printf("key=%s found=%t winner=%v\n", key, ok, val)
}
var wg sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does Deduplicate Concurrent Writes With sync.Map LoadOrStore print when run?
No setup needed: run the file and look for labeled lines like `winners=`, `key=` in the output.