programming

Getting to Know Sync Map on Golang

Introduction to sync.Map

This sync.Map is actually very similar to the regular Generic Golangnya map, but the difference is that this map is safe to use during concurrent goroutines.

sync.Map is a map implementation that allows us to safely access and modify its data from multiple goroutines. This will provide an efficient way to store and retrieve values with locks.

In addition, sync.Map uses a combination of hash-based atomic, sync.RWMutex and struct operations to ensure the data remains consistent and accessible even while multiple goroutines modify the map.

Why should we use sync.Map?

sync.Map is suitable for those of us who often use high concurrence where many goroutines access and modify data together.

It is important to note that sync.Map cannot guarantee the data is sequential when it is output and also key cannot be processed in a specific order. In addition, unlike in a regular goal, sync.Map does not support some goal operations such as delete, range. So, we need to be careful in using this type.

Method Usage

Some of the methods available in sync.Map are as follows:

  • Load(key interface{}) (value interface{}, ok bool) is used to retrieve data from an initialized map
  • Store(key, value interface{}) is used to store data into the map with the specified key.
  • Delete(key interface{}) is used to delete data with a specific key in a map.
  • Range(f func(key, value interface{}) bool) is used to output data with the condition of whether or not there is data with the key we are looking for.
  • LoadOrStore(key, value inteface{})(actual interface{}, loaded bool) is used to retrieve data from a map but if it is not there it will automatically store it into the map and then output the actual map.

Implementation and sample of sync.Map

Let’s take a look at the implementation code below.

func main() {
	var data sync.Map
	var AddToMap = func(value int) {
		data.Store(value, value)
	}

	for i := 0; i < 100; i++ {
		go AddToMap(i)
	}

	time.Sleep(5 * time.Second)
	data.Range(func(key, value interface{}) bool {
		fmt.Println(key, ":", value)
		return true
	})
}

So, the result of the above code if we run it will be like below

21 : 21
63 : 63
...
...
9 : 9
19 : 1

We can see that the data output is not sequential because actually all the data stored in the map is irregular as it is stored using goroutines.

Conclusion

sync.Map is a complex struct that is generally used for reading and another one for storing new elements. This sync.Map has the map + sync.RWMutex approach in its metric, but it can also be the best from the reading side. When there is data synchronization from reading and updating then sync.Map has the upper hand.

comments powered by Disqus