Skip to content

Commit

Permalink
fix Forget blocks forever if the key does not exist.
Browse files Browse the repository at this point in the history
  • Loading branch information
shogo82148 committed Feb 13, 2024
1 parent db59cd6 commit 64fc1f2
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
10 changes: 6 additions & 4 deletions memoize.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func newPanicError(v interface{}) error {

// Group represents a class of work and forms a namespace in which units of work can be executed with duplicate suppression.
type Group[K comparable, V any] struct {
mu sync.Mutex // protects m
mu sync.RWMutex // protects m
m map[K]*entry[V] // lazy initialized
}

Expand Down Expand Up @@ -267,15 +267,17 @@ func do[K comparable, V any](g *Group[K, V], e *entry[V], c *call[V], key K, fn
// to Do for this key will call the function rather than waiting for
// an earlier call to complete.
func (g *Group[K, V]) Forget(key K) {
g.mu.Lock()
g.mu.RLock()
defer g.mu.RUnlock()

e, ok := g.m[key]
if !ok {
return
}
e.mu.Lock()
defer e.mu.Unlock()

e.forgot = true
e.mu.Unlock()
g.mu.Unlock()
}

// GC deletes the expired items from the cache.
Expand Down
3 changes: 3 additions & 0 deletions memoize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,9 @@ func BenchmarkDo(b *testing.B) {
func TestForget(t *testing.T) {
var g Group[string, int]

// Forget should do nothing if the key does not exist.
g.Forget("key")

var (
firstStarted = make(chan struct{})
unblockFirst = make(chan struct{})
Expand Down

0 comments on commit 64fc1f2

Please sign in to comment.