// Copyright 2016 The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34package generic_sync56import (7"sync"8"sync/atomic"9"unsafe"10)1112// MapOf is like a Go map[interface{}]interface{} but is safe for concurrent use13// by multiple goroutines without additional locking or coordination.14// Loads, stores, and deletes run in amortized constant time.15//16// The MapOf type is specialized. Most code should use a plain Go map instead,17// with separate locking or coordination, for better type safety and to make it18// easier to maintain other invariants along with the map content.19//20// The MapOf type is optimized for two common use cases: (1) when the entry for a given21// key is only ever written once but read many times, as in caches that only grow,22// or (2) when multiple goroutines read, write, and overwrite entries for disjoint23// sets of keys. In these two cases, use of a MapOf may significantly reduce lock24// contention compared to a Go map paired with a separate Mutex or RWMutex.25//26// The zero MapOf is empty and ready for use. A MapOf must not be copied after first use.27type MapOf[K comparable, V any] struct {28mu sync.Mutex2930// read contains the portion of the map's contents that are safe for31// concurrent access (with or without mu held).32//33// The read field itself is always safe to load, but must only be stored with34// mu held.35//36// Entries stored in read may be updated concurrently without mu, but updating37// a previously-expunged entry requires that the entry be copied to the dirty38// map and unexpunged with mu held.39read atomic.Value // readOnly4041// dirty contains the portion of the map's contents that require mu to be42// held. To ensure that the dirty map can be promoted to the read map quickly,43// it also includes all of the non-expunged entries in the read map.44//45// Expunged entries are not stored in the dirty map. An expunged entry in the46// clean map must be unexpunged and added to the dirty map before a new value47// can be stored to it.48//49// If the dirty map is nil, the next write to the map will initialize it by50// making a shallow copy of the clean map, omitting stale entries.51dirty map[K]*entry[V]5253// misses counts the number of loads since the read map was last updated that54// needed to lock mu to determine whether the key was present.55//56// Once enough misses have occurred to cover the cost of copying the dirty57// map, the dirty map will be promoted to the read map (in the unamended58// state) and the next store to the map will make a new dirty copy.59misses int60}6162// readOnly is an immutable struct stored atomically in the MapOf.read field.63type readOnly[K comparable, V any] struct {64m map[K]*entry[V]65amended bool // true if the dirty map contains some key not in m.66}6768// expunged is an arbitrary pointer that marks entries which have been deleted69// from the dirty map.70var expunged = unsafe.Pointer(new(interface{}))7172// An entry is a slot in the map corresponding to a particular key.73type entry[V any] struct {74// p points to the interface{} value stored for the entry.75//76// If p == nil, the entry has been deleted and m.dirty == nil.77//78// If p == expunged, the entry has been deleted, m.dirty != nil, and the entry79// is missing from m.dirty.80//81// Otherwise, the entry is valid and recorded in m.read.m[key] and, if m.dirty82// != nil, in m.dirty[key].83//84// An entry can be deleted by atomic replacement with nil: when m.dirty is85// next created, it will atomically replace nil with expunged and leave86// m.dirty[key] unset.87//88// An entry's associated value can be updated by atomic replacement, provided89// p != expunged. If p == expunged, an entry's associated value can be updated90// only after first setting m.dirty[key] = e so that lookups using the dirty91// map find the entry.92p unsafe.Pointer // *interface{}93}9495func newEntry[V any](i V) *entry[V] {96return &entry[V]{p: unsafe.Pointer(&i)}97}9899// Load returns the value stored in the map for a key, or nil if no100// value is present.101// The ok result indicates whether value was found in the map.102func (m *MapOf[K, V]) Load(key K) (value V, ok bool) {103read, _ := m.read.Load().(readOnly[K, V])104e, ok := read.m[key]105if !ok && read.amended {106m.mu.Lock()107// Avoid reporting a spurious miss if m.dirty got promoted while we were108// blocked on m.mu. (If further loads of the same key will not miss, it's109// not worth copying the dirty map for this key.)110read, _ = m.read.Load().(readOnly[K, V])111e, ok = read.m[key]112if !ok && read.amended {113e, ok = m.dirty[key]114// Regardless of whether the entry was present, record a miss: this key115// will take the slow path until the dirty map is promoted to the read116// map.117m.missLocked()118}119m.mu.Unlock()120}121if !ok {122return value, false123}124return e.load()125}126127func (m *MapOf[K, V]) Has(key K) bool {128_, ok := m.Load(key)129return ok130}131132func (e *entry[V]) load() (value V, ok bool) {133p := atomic.LoadPointer(&e.p)134if p == nil || p == expunged {135return value, false136}137return *(*V)(p), true138}139140// Store sets the value for a key.141func (m *MapOf[K, V]) Store(key K, value V) {142read, _ := m.read.Load().(readOnly[K, V])143if e, ok := read.m[key]; ok && e.tryStore(&value) {144return145}146147m.mu.Lock()148read, _ = m.read.Load().(readOnly[K, V])149if e, ok := read.m[key]; ok {150if e.unexpungeLocked() {151// The entry was previously expunged, which implies that there is a152// non-nil dirty map and this entry is not in it.153m.dirty[key] = e154}155e.storeLocked(&value)156} else if e, ok := m.dirty[key]; ok {157e.storeLocked(&value)158} else {159if !read.amended {160// We're adding the first new key to the dirty map.161// Make sure it is allocated and mark the read-only map as incomplete.162m.dirtyLocked()163m.read.Store(readOnly[K, V]{m: read.m, amended: true})164}165m.dirty[key] = newEntry(value)166}167m.mu.Unlock()168}169170// tryStore stores a value if the entry has not been expunged.171//172// If the entry is expunged, tryStore returns false and leaves the entry173// unchanged.174func (e *entry[V]) tryStore(i *V) bool {175for {176p := atomic.LoadPointer(&e.p)177if p == expunged {178return false179}180if atomic.CompareAndSwapPointer(&e.p, p, unsafe.Pointer(i)) {181return true182}183}184}185186// unexpungeLocked ensures that the entry is not marked as expunged.187//188// If the entry was previously expunged, it must be added to the dirty map189// before m.mu is unlocked.190func (e *entry[V]) unexpungeLocked() (wasExpunged bool) {191return atomic.CompareAndSwapPointer(&e.p, expunged, nil)192}193194// storeLocked unconditionally stores a value to the entry.195//196// The entry must be known not to be expunged.197func (e *entry[V]) storeLocked(i *V) {198atomic.StorePointer(&e.p, unsafe.Pointer(i))199}200201// LoadOrStore returns the existing value for the key if present.202// Otherwise, it stores and returns the given value.203// The loaded result is true if the value was loaded, false if stored.204func (m *MapOf[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {205// Avoid locking if it's a clean hit.206read, _ := m.read.Load().(readOnly[K, V])207if e, ok := read.m[key]; ok {208actual, loaded, ok := e.tryLoadOrStore(value)209if ok {210return actual, loaded211}212}213214m.mu.Lock()215read, _ = m.read.Load().(readOnly[K, V])216if e, ok := read.m[key]; ok {217if e.unexpungeLocked() {218m.dirty[key] = e219}220actual, loaded, _ = e.tryLoadOrStore(value)221} else if e, ok := m.dirty[key]; ok {222actual, loaded, _ = e.tryLoadOrStore(value)223m.missLocked()224} else {225if !read.amended {226// We're adding the first new key to the dirty map.227// Make sure it is allocated and mark the read-only map as incomplete.228m.dirtyLocked()229m.read.Store(readOnly[K, V]{m: read.m, amended: true})230}231m.dirty[key] = newEntry(value)232actual, loaded = value, false233}234m.mu.Unlock()235236return actual, loaded237}238239// tryLoadOrStore atomically loads or stores a value if the entry is not240// expunged.241//242// If the entry is expunged, tryLoadOrStore leaves the entry unchanged and243// returns with ok==false.244func (e *entry[V]) tryLoadOrStore(i V) (actual V, loaded, ok bool) {245p := atomic.LoadPointer(&e.p)246if p == expunged {247return actual, false, false248}249if p != nil {250return *(*V)(p), true, true251}252253// Copy the interface after the first load to make this method more amenable254// to escape analysis: if we hit the "load" path or the entry is expunged, we255// shouldn'V bother heap-allocating.256ic := i257for {258if atomic.CompareAndSwapPointer(&e.p, nil, unsafe.Pointer(&ic)) {259return i, false, true260}261p = atomic.LoadPointer(&e.p)262if p == expunged {263return actual, false, false264}265if p != nil {266return *(*V)(p), true, true267}268}269}270271// Delete deletes the value for a key.272func (m *MapOf[K, V]) Delete(key K) {273read, _ := m.read.Load().(readOnly[K, V])274e, ok := read.m[key]275if !ok && read.amended {276m.mu.Lock()277read, _ = m.read.Load().(readOnly[K, V])278e, ok = read.m[key]279if !ok && read.amended {280delete(m.dirty, key)281}282m.mu.Unlock()283}284if ok {285e.delete()286}287}288289func (e *entry[V]) delete() (hadValue bool) {290for {291p := atomic.LoadPointer(&e.p)292if p == nil || p == expunged {293return false294}295if atomic.CompareAndSwapPointer(&e.p, p, nil) {296return true297}298}299}300301// Range calls f sequentially for each key and value present in the map.302// If f returns false, range stops the iteration.303//304// Range does not necessarily correspond to any consistent snapshot of the MapOf's305// contents: no key will be visited more than once, but if the value for any key306// is stored or deleted concurrently, Range may reflect any mapping for that key307// from any point during the Range call.308//309// Range may be O(N) with the number of elements in the map even if f returns310// false after a constant number of calls.311func (m *MapOf[K, V]) Range(f func(key K, value V) bool) {312// We need to be able to iterate over all of the keys that were already313// present at the start of the call to Range.314// If read.amended is false, then read.m satisfies that property without315// requiring us to hold m.mu for a long time.316read, _ := m.read.Load().(readOnly[K, V])317if read.amended {318// m.dirty contains keys not in read.m. Fortunately, Range is already O(N)319// (assuming the caller does not break out early), so a call to Range320// amortizes an entire copy of the map: we can promote the dirty copy321// immediately!322m.mu.Lock()323read, _ = m.read.Load().(readOnly[K, V])324if read.amended {325read = readOnly[K, V]{m: m.dirty}326m.read.Store(read)327m.dirty = nil328m.misses = 0329}330m.mu.Unlock()331}332333for k, e := range read.m {334v, ok := e.load()335if !ok {336continue337}338if !f(k, v) {339break340}341}342}343344// Values returns a slice of the values in the map.345func (m *MapOf[K, V]) Values() []V {346var values []V347m.Range(func(key K, value V) bool {348values = append(values, value)349return true350})351return values352}353354func (m *MapOf[K, V]) Count() int {355return len(m.dirty)356}357358func (m *MapOf[K, V]) Empty() bool {359return m.Count() == 0360}361362func (m *MapOf[K, V]) ToMap() map[K]V {363ans := make(map[K]V)364m.Range(func(key K, value V) bool {365ans[key] = value366return true367})368return ans369}370371func (m *MapOf[K, V]) Clear() {372m.Range(func(key K, value V) bool {373m.Delete(key)374return true375})376}377378func (m *MapOf[K, V]) missLocked() {379m.misses++380if m.misses < len(m.dirty) {381return382}383m.read.Store(readOnly[K, V]{m: m.dirty})384m.dirty = nil385m.misses = 0386}387388func (m *MapOf[K, V]) dirtyLocked() {389if m.dirty != nil {390return391}392393read, _ := m.read.Load().(readOnly[K, V])394m.dirty = make(map[K]*entry[V], len(read.m))395for k, e := range read.m {396if !e.tryExpungeLocked() {397m.dirty[k] = e398}399}400}401402func (e *entry[V]) tryExpungeLocked() (isExpunged bool) {403p := atomic.LoadPointer(&e.p)404for p == nil {405if atomic.CompareAndSwapPointer(&e.p, nil, expunged) {406return true407}408p = atomic.LoadPointer(&e.p)409}410return p == expunged411}412413414