diff --git a/concurrency/keyed_locker.go b/concurrency/keyed_locker.go index c222d70..852abf0 100644 --- a/concurrency/keyed_locker.go +++ b/concurrency/keyed_locker.go @@ -214,14 +214,17 @@ func NewTryKeyedLocker[K comparable]() *TryKeyedLocker[K] { // Play: https://go.dev/play/p/VG9qLvyetE2 func (l *TryKeyedLocker[K]) TryLock(key K) bool { l.mu.Lock() + defer l.mu.Unlock() lock, ok := l.locks[key] if !ok { lock = &casMutex{} l.locks[key] = lock } - l.mu.Unlock() + // TryLock must run while l.mu is held. Otherwise Unlock can delete this entry + // from the map before the lock is taken, and a later TryLock for the same key + // would create a second entry and succeed while this one is still held. return lock.TryLock() } diff --git a/concurrency/keyed_locker_test.go b/concurrency/keyed_locker_test.go index 5c07752..dfefeb2 100644 --- a/concurrency/keyed_locker_test.go +++ b/concurrency/keyed_locker_test.go @@ -4,6 +4,7 @@ import ( "context" "strconv" "sync" + "sync/atomic" "testing" "time" @@ -228,3 +229,34 @@ func TestTryKeyedLocker_ParallelTry(t *testing.T) { assert.Equal(5, count) assert.Equal(0, len(locker.locks)) } + +func TestTryKeyedLocker_MutualExclusionUnderContention(t *testing.T) { + t.Parallel() + + locker := NewTryKeyedLocker[string]() + + var holders, violations int32 + var wg sync.WaitGroup + + for g := 0; g < 8; g++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 20000; i++ { + if !locker.TryLock("key") { + continue + } + if atomic.AddInt32(&holders, 1) > 1 { + atomic.AddInt32(&violations, 1) + } + atomic.AddInt32(&holders, -1) + locker.Unlock("key") + } + }() + } + wg.Wait() + + if v := atomic.LoadInt32(&violations); v != 0 { + t.Fatalf("the lock was held by more than one goroutine %d times", v) + } +}