Skip to content

Instantly share code, notes, and snippets.

@myuon
Created October 8, 2023 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myuon/7c5ec2ad956418ff3c8036d64793b261 to your computer and use it in GitHub Desktop.
Save myuon/7c5ec2ad956418ff3c8036d64793b261 to your computer and use it in GitHub Desktop.
package golangglobalcachewithmutex
import "sync"
type MemCache[K comparable, T any] struct {
cache map[K]T
mutex *sync.Mutex
}
func (m MemCache[K, T]) Get(key K) (T, bool) {
m.mutex.Lock()
defer m.mutex.Unlock()
value, ok := m.cache[key]
return value, ok
}
func (m MemCache[K, T]) Set(key K, value T) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.cache[key] = value
}
func (m MemCache[K, T]) Delete(key K) {
m.mutex.Lock()
defer m.mutex.Unlock()
delete(m.cache, key)
}
func NewMemCache[K comparable, T any]() MemCache[K, T] {
return MemCache[K, T]{
cache: make(map[K]T),
mutex: &sync.Mutex{},
}
}
package golangglobalcachewithmutex
import "testing"
func Test_Get(t *testing.T) {
cache := NewMemCache[string, int]()
cache.Set("foo", 1)
value, ok := cache.Get("foo")
if !ok {
panic("value should exist")
}
if value != 1 {
panic("value should be 1")
}
}
func Test_Get_WhenKeyDoesNotExist(t *testing.T) {
cache := NewMemCache[string, int]()
_, ok := cache.Get("foo")
if ok {
panic("value should not exist")
}
}
func Test_Set(t *testing.T) {
cache := NewMemCache[string, int]()
cache.Set("foo", 1)
value, ok := cache.Get("foo")
if !ok {
panic("value should exist")
}
if value != 1 {
panic("value should be 1")
}
}
func Test_Delete(t *testing.T) {
cache := NewMemCache[string, int]()
cache.Set("foo", 1)
cache.Delete("foo")
_, ok := cache.Get("foo")
if ok {
panic("value should not exist")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment