Junior — Middle
What measures are taken to prevent the occurrence of ConcurrentModificationException when modifying a Map object from multiple threads simultaneously?
sobes.tech AI
Answer from AI
In Go, a map is not thread-safe for concurrent read and write operations from multiple goroutines. To avoid ConcurrentModificationException (the Go equivalent — panic on concurrent access), the following measures are used:
- Using a mutex (
sync.Mutexorsync.RWMutex) to synchronize access to the map. - Using thread-safe data structures, such as
sync.Map, which is specifically designed for concurrent access.
Example with a mutex:
var mu sync.RWMutex
var m = make(map[string]int)
func read(key string) int {
mu.RLock()
defer mu.RUnlock()
return m[key]
}
func write(key string, value int) {
mu.Lock()
defer mu.Unlock()
m[key] = value
}
Using sync.Map:
var m sync.Map
func write(key string, value int) {
m.Store(key, value)
}
func read(key string) (int, bool) {
val, ok := m.Load(key)
if !ok {
return 0, false
}
return val.(int), true
}
Thus, to prevent errors during concurrent access to a map, synchronization or specialized structures should be used.