sync_map

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2025 License: BSD-3-Clause Imports: 3 Imported by: 4

README

Go Reference

sync-map

A fork of Go's sync.Map, but with generics.

Why...

... not just use sync.Map?

Declaring the types of variables in your code helps document their usage and prevent programming errors. It's unfortunate that sync.Map predates generics - now that we have them I think even people who want to use a concurrent map should have access to type checking.

... not just create a wrapper around sync.Map to provide type-safety?

Putting value behind a pointer to the heap has a cost - probably a bigger one than you expect. If you're working with values of mixed types, this may be necessary. If you only want to work with values of one type, it just adds overhead. Modifying the map to support generics natively allows us to get (sometimes substantially) better performance by using simple types as keys.

... not use my favorite concurrent map implementation?

sync.Map is not the fastest possible implementation of a concurrent map. However, it is relatively simple and its performance characteristics are well-understood and optimized for common use-cases. In the past, I have tested packages advertising a faster concurrent map and struggled to get the performance to equal sync.Map.

This may be caused in part by the opaque way in which Go handles hashing - the Go runtime defines its own hash function in the runtime for its internal maps, but other map implementations require a user-defined hash function. Historically, Go has not provided a good, easy way to implement this. Recent changes to the maphash package may have improved this.

Regardless of the reason, though, it makes sense to provide the same algorithm but with support for generics to ensure the performance characteristics are not worse than the default option.

... are CompareAndSwap and CompareAndDelete functions, not methods?

CompareAndSwap and CompareAndDelete are useful operations to support on a concurrent map. These operations require the values in the map to be comparable - otherwise, how will you compare them to know if you should swap or delete the values? However, we also want to be able to have Map store non-comparable values.

The compromise is to remove these methods from the regular Map type, and create functions that can apply a tighter bound on the value type.

... not use the new sync.Map implementation from Go 1.24?

In 1.24, Go updated the implementation of sync.Map to use a concurrent hash-trie. The underlying interal HashTrieMap already supports generics, it's just not exported in a way that makes the generic version available. I would like to provide an exposed version of this. However, the HashTrieMap implementation uses internal/abi functionality, which isn't accessible or safe to re-implement outside the standard library, so I don't know that there's a good way to do this. Hopefully sync/v2 with an officially-supported generic map is coming soon.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompareAndDelete

func CompareAndDelete[K comparable, V comparable](m *Map[K, V], key K, old V) (deleted bool)

CompareAndDelete deletes the entry for key if its value is equal to old. The old value must be of a comparable type.

If there is no current value for key in the map, CompareAndDelete returns false (even if the old value is the zero value of V).

func CompareAndSwap

func CompareAndSwap[K comparable, V comparable](m *Map[K, V], key K, old, new V) (swapped bool)

CompareAndSwap swaps the old and new values for key if the value stored in the map is equal to old. The old value must be of a comparable type.

Types

type Map

type Map[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map is like a Go map[K]V but is safe for concurrent use by multiple goroutines without additional locking or coordination. Loads, stores, and deletes run in amortized constant time.

The Map type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content.

The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate [Mutex] or [RWMutex].

The zero Map is empty and ready for use. A Map must not be copied after first use.

In the terminology of the Go memory model, Map arranges that a write operation “synchronizes before” any read operation that observes the effect of the write, where read and write operations are defined as follows. Map.Load, Map.LoadAndDelete, Map.LoadOrStore, and Map.Swap are read operations; Map.Delete, Map.LoadAndDelete, Map.Store, and Map.Swap are write operations; Map.LoadOrStore is a write operation when it returns loaded set to false.

func (*Map[K, V]) Clear

func (m *Map[K, V]) Clear()

Clear deletes all the entries, resulting in an empty Map.

func (*Map[K, V]) Delete

func (m *Map[K, V]) Delete(key K)

Delete deletes the value for a key.

func (*Map[K, V]) Load

func (m *Map[K, V]) Load(key K) (value V, ok bool)

Load returns the value stored in the map for a key, or nil if no value is present. The ok result indicates whether value was found in the map.

func (*Map[K, V]) LoadAndDelete

func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool)

LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.

func (*Map[K, V]) LoadOrStore

func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

func (*Map[K, V]) Range

func (m *Map[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently (including by f), Range may reflect any mapping for that key from any point during the Range call. Range does not block other methods on the receiver; even f itself may call any method on m.

Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.

func (*Map[K, V]) Store

func (m *Map[K, V]) Store(key K, value V)

Store sets the value for a key.

func (*Map[K, V]) Swap

func (m *Map[K, V]) Swap(key K, value V) (previous V, loaded bool)

Swap swaps the value for a key and returns the previous value if any. The loaded result reports whether the key was present.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL