Skip to content

Commit 12abf03

Browse files
committed
Shrink mutation detection critical section
1 parent 94f69bd commit 12abf03

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

staging/src/k8s.io/client-go/tools/cache/mutation_detector.go

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,13 @@ type defaultCacheMutationDetector struct {
6868
name string
6969
period time.Duration
7070

71-
lock sync.Mutex
71+
// compareLock ensures only a single call to CompareObjects runs at a time
72+
compareObjectsLock sync.Mutex
73+
74+
// addLock guards addedObjs between AddObject and CompareObjects
75+
addedObjsLock sync.Mutex
76+
addedObjs []cacheObj
77+
7278
cachedObjs []cacheObj
7379

7480
retainDuration time.Duration
@@ -118,15 +124,22 @@ func (d *defaultCacheMutationDetector) AddObject(obj interface{}) {
118124
if obj, ok := obj.(runtime.Object); ok {
119125
copiedObj := obj.DeepCopyObject()
120126

121-
d.lock.Lock()
122-
defer d.lock.Unlock()
123-
d.cachedObjs = append(d.cachedObjs, cacheObj{cached: obj, copied: copiedObj})
127+
d.addedObjsLock.Lock()
128+
defer d.addedObjsLock.Unlock()
129+
d.addedObjs = append(d.addedObjs, cacheObj{cached: obj, copied: copiedObj})
124130
}
125131
}
126132

127133
func (d *defaultCacheMutationDetector) CompareObjects() {
128-
d.lock.Lock()
129-
defer d.lock.Unlock()
134+
d.compareObjectsLock.Lock()
135+
defer d.compareObjectsLock.Unlock()
136+
137+
// move addedObjs into cachedObjs under lock
138+
// this keeps the critical section small to avoid blocking AddObject while we compare cachedObjs
139+
d.addedObjsLock.Lock()
140+
d.cachedObjs = append(d.cachedObjs, d.addedObjs...)
141+
d.addedObjs = nil
142+
d.addedObjsLock.Unlock()
130143

131144
altered := false
132145
for i, obj := range d.cachedObjs {

0 commit comments

Comments
 (0)