Load
and Delete
on sync.Map
should be replaced with LoadAndDelete
GO-W4011LoadAndDelete
is a single atomic operation, unlike calling Delete
after
Load
. This prevents a condition where the goroutine is preempted, and the key
is deleted by another goroutine.
package main
import (
"sync"
)
func foo(m *sync.Map, k any) {
v, ok := m.Load(k)
if ok {
m.Delete(k)
// ...
}
}
package main
import (
"sync"
)
func foo(m *sync.Map, k any) {
v, deleted := m.LoadAndDelete(k)
if deleted {
// ...
}
}