Skip to content

Commit 6feff7c

Browse files
committed
Use sync.Pool to reduce GC pressure
The benchmarks show a reduction in allocs without significant performance regression. Signed-off-by: Cory Snider <csnider@mirantis.com>
1 parent 3929ae6 commit 6feff7c

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

mutexmap.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ type lockCtr struct {
2424
waiters atomic.Int32 // Number of callers waiting to acquire the lock
2525
}
2626

27+
var lockCtrPool = sync.Pool{New: func() any { return new(lockCtr) }}
28+
2729
// Lock locks a mutex with the given name.
2830
func (l *MutexMap[T]) Lock(key T) {
2931
l.mu.Lock()
@@ -33,7 +35,7 @@ func (l *MutexMap[T]) Lock(key T) {
3335

3436
nameLock, exists := l.locks[key]
3537
if !exists {
36-
nameLock = &lockCtr{}
38+
nameLock = lockCtrPool.Get().(*lockCtr)
3739
l.locks[key] = nameLock
3840
}
3941

@@ -61,6 +63,7 @@ func (l *MutexMap[T]) Unlock(key T) {
6163

6264
if nameLock.waiters.Load() <= 0 {
6365
delete(l.locks, key)
66+
defer lockCtrPool.Put(nameLock)
6467
}
6568
nameLock.Unlock()
6669
}

rwmutexmap.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ type rwlockCtr struct {
2020
waiters atomic.Int32 // Number of callers waiting to acquire the lock
2121
}
2222

23+
var rwlockCtrPool = sync.Pool{New: func() any { return new(rwlockCtr) }}
24+
2325
func (l *RWMutexMap[T]) doLock(key T, op func(*sync.RWMutex)) {
2426
l.mu.Lock()
2527
if l.locks == nil {
@@ -28,7 +30,7 @@ func (l *RWMutexMap[T]) doLock(key T, op func(*sync.RWMutex)) {
2830

2931
nameLock, exists := l.locks[key]
3032
if !exists {
31-
nameLock = &rwlockCtr{}
33+
nameLock = rwlockCtrPool.Get().(*rwlockCtr)
3234
l.locks[key] = nameLock
3335
}
3436

@@ -64,6 +66,7 @@ func (l *RWMutexMap[T]) doUnlock(key T, op func(*sync.RWMutex)) {
6466

6567
if nameLock.waiters.Load() <= 0 {
6668
delete(l.locks, key)
69+
defer rwlockCtrPool.Put(nameLock)
6770
}
6871
op(&nameLock.RWMutex)
6972
}

0 commit comments

Comments
 (0)