How to implement a concurrent-safe data cache in Go?

To implement a concurrent-safe data cache in Go, you can use the sync package from the Go standard library. Here's an example implementation:

  1. Define a struct that represents the cache and holds the data along with a mutex for synchronization:
type DataCache struct { data map[string]interface{} mutex sync.RWMutex }
  1. Create methods to perform operations on the cache. Some common methods are:

    • Get(key string) (interface{}, bool): Retrieves the data for the given key from the cache.
    • Set(key string, value interface{}): Stores the given value in the cache for the specified key.
    • Delete(key string): Removes the specified key and its associated value from the cache.
    • Clear(): Clears the entire cache.
func (c *DataCache) Get(key string) (interface{}, bool) { c.mutex.RLock() defer c.mutex.RUnlock() value, ok := c.data[key] return value, ok } func (c *DataCache) Set(key string, value interface{}) { c.mutex.Lock() defer c.mutex.Unlock() c.data[key] = value } func (c *DataCache) Delete(key string) { c.mutex.Lock() defer c.mutex.Unlock() delete(c.data, key) } func (c *DataCache) Clear() { c.mutex.Lock() defer c.mutex.Unlock() c.data = make(map[string]interface{}) }
  1. Initialize the cache and use it in your code:
func main() { cache := &DataCache{ data: make(map[string]interface{}), } // Access the cache concurrently go func() { cache.Set("key1", "value1") value, ok := cache.Get("key1") // ... }() go func() { value, ok := cache.Get("key1") // ... cache.Delete("key1") // ... }() // ... }

By using a sync.RWMutex, the cache allows multiple readers to access data concurrently while ensuring exclusive access during write operations.