Skip to content

Commit 8fa1510

Browse files
committed
chore: use syncmap instead of custom locker
Signed-off-by: Javier Aliaga <[email protected]>
1 parent 7706cc6 commit 8fa1510

File tree

1 file changed

+8
-39
lines changed

1 file changed

+8
-39
lines changed

samples/taskexecutionid/taskexecutionid.go

Lines changed: 8 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88
"log"
99
"sync"
10+
"sync/atomic"
1011
"time"
1112

1213
"github.com/dapr/durabletask-go/backend"
@@ -102,56 +103,24 @@ func RetryActivityOrchestrator(ctx *task.OrchestrationContext) (any, error) {
102103
return nil, nil
103104
}
104105

105-
type Counter struct {
106-
c int32
107-
lock sync.Mutex
108-
}
109-
110-
func (c *Counter) Increment() {
111-
c.lock.Lock()
112-
defer c.lock.Unlock()
113-
c.c++
114-
}
115-
116-
func (c *Counter) GetValue() int32 {
117-
c.lock.Lock()
118-
defer c.lock.Unlock()
119-
return c.c
120-
}
121-
122106
var (
123-
counters = make(map[string]*Counter)
124-
countersLock sync.RWMutex
107+
counters = sync.Map{}
125108
)
126109

127110
// getCounter returns a Counter instance for the specified taskExecutionId.
128111
// If no counter exists for the taskExecutionId, a new one is created.
129-
func getCounter(taskExecutionId string) *Counter {
130-
countersLock.RLock()
131-
counter, exists := counters[taskExecutionId]
132-
countersLock.RUnlock()
133-
134-
if !exists {
135-
countersLock.Lock()
136-
// Check again to handle race conditions
137-
counter, exists = counters[taskExecutionId]
138-
if !exists {
139-
counter = &Counter{}
140-
counters[taskExecutionId] = counter
141-
}
142-
countersLock.Unlock()
143-
}
144-
145-
return counter
112+
func getCounter(taskExecutionId string) *atomic.Int32 {
113+
counter, _ := counters.LoadOrStore(taskExecutionId, &atomic.Int32{})
114+
return counter.(*atomic.Int32)
146115
}
147116

148117
func RandomFailActivity(ctx task.ActivityContext) (any, error) {
149118
log.Println(fmt.Sprintf("#### [%v] activity %v failure", ctx.GetTaskExecutionId(), ctx.GetTaskID()))
150-
119+
counter := getCounter(ctx.GetTaskExecutionId())
151120
// The activity should fail 5 times before succeeding.
152-
if getCounter(ctx.GetTaskExecutionId()).GetValue() != 5 {
121+
if counter.Load() != 5 {
153122
log.Println("random activity failure")
154-
getCounter(ctx.GetTaskExecutionId()).Increment()
123+
counter.Add(1)
155124
return "", errors.New("random activity failure")
156125
}
157126

0 commit comments

Comments
 (0)