

Within this time-gap, multiple goroutines could have updated the storage multiple times all of which will be lost when the update completes (following the initial load operation). If we were to just use Load, there would always be a time-gap between calling Load and computing the next state before storing it. If the previous value was value, then the next value held by the key will be value + 1. If there was no record associated with the given key, a pointer to the new record is stored. If Add wasn’t an update operation that depends on the previous state, we might be better off with just using Store. LoadOrStore ensures that a record associated with a key is created for the first time precisely once, regardless of how many goroutines simultaneously tries to create a record. This can only be achieved with LoadAndDelete and LoadOrStore, or we may have to explicitly synchronize calls to Load and Store with locks:Įnter fullscreen mode Exit fullscreen mode Even when these values are updated concurrently, the final value stored by any key will always be accurate. These values are update-able, and lets you add arbitrary values to them. In the following example, the structure Counter is supposed to hold integer values associated with a string. Using sync.Map to store integers that can be incremented or decremented concurrently:

The same way, without LoadAndDelete it is impossible for a goroutine to delete and retrieve the most recently stored (or modified) record without using additional locks to synchronize Load and Delete.

Theoretically, without LoadOrStore, it is impossible to have multiple goroutines simultaneously create a record associated with a key precisely once without the use of additional locks. To anyone new to concurrency, it might not seem obvious that just the methods Load, Store and Delete cannot be used to perform the basic read, write and delete operations commonly done using the regular non-thread-safe map from within a single goroutine. Read this to understand how sync.Map works internally:
