Skip to content

Commit 3b077e2

Browse files
devfeelAI Assistant
andauthored
fix: use defer Unlock in Incr/Decr to prevent lock leak (#312)
* chore: bump version to 1.8.3 * fix: use defer Unlock in Incr/Decr to prevent lock leak (#311) - Add defer ca.Unlock() in Incr() and Decr() functions - Fix potential deadlock when error occurs in type switch - Pass race detection test Co-authored-by: AI Assistant <ai@devfeel.io> --------- Co-authored-by: AI Assistant <ai@devfeel.io>
1 parent 89df748 commit 3b077e2

File tree

1 file changed

+2
-3
lines changed

1 file changed

+2
-3
lines changed

cache/runtime/cache_runtime.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ func (ca *RuntimeCache) initValue(key string, value interface{}, ttl int64) erro
122122
// Incr increase int64 counter in runtime cache.
123123
func (ca *RuntimeCache) Incr(key string) (int64, error) {
124124
ca.Lock()
125+
defer ca.Unlock()
125126
itemObj, ok := ca.items.Load(key)
126127
if !ok {
127128
// if not exists, auto set new with 0
@@ -148,15 +149,14 @@ func (ca *RuntimeCache) Incr(key string) (int64, error) {
148149
return 0, errors.New("item val is not (u)int (u)int32 (u)int64")
149150
}
150151

151-
ca.Unlock()
152-
153152
val, _ := strconv.ParseInt(fmt.Sprint(item.value), 10, 64)
154153
return val, nil
155154
}
156155

157156
// Decr decrease counter in runtime cache.
158157
func (ca *RuntimeCache) Decr(key string) (int64, error) {
159158
ca.Lock()
159+
defer ca.Unlock()
160160
itemObj, ok := ca.items.Load(key)
161161
if !ok {
162162
// if not exists, auto set new with 0
@@ -194,7 +194,6 @@ func (ca *RuntimeCache) Decr(key string) (int64, error) {
194194
default:
195195
return 0, errors.New("item val is not int int64 int32")
196196
}
197-
ca.Unlock()
198197

199198
val, _ := strconv.ParseInt(fmt.Sprint(item.value), 10, 64)
200199
return val, nil

0 commit comments

Comments
 (0)