fix(package): [concurrency] hold the map lock while taking the try lock (#417)

* fix(package): [concurrency] hold the map lock while taking the try lock

* test(package): [concurrency] check TryKeyedLocker mutual exclusion
This commit is contained in:
Lee Sang Gyu authored and GitHub committed 2026-11-09 17:36:58 +08:00
1 parent d859b91c57
commit b09d6af4a4
2 files changed
+36 -1

No files matched your search

+4 -1
View File
@@ -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()
}