-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathbatch_sender_test.go
More file actions
43 lines (37 loc) · 1001 Bytes
/
batch_sender_test.go
File metadata and controls
43 lines (37 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package batchsender
import (
"sync"
"testing"
"time"
)
// This test verifies there is no data race between Send() and the timer-triggered flush.
func TestSend_ConcurrentWithTimerFlush(t *testing.T) {
// The race occurs when:
// 1. a Send() call schedules a timer via time.AfterFunc
// 2. the timer fires and calls flush() on a separate goroutine
// 3. another Send() reads bs.items concurrently.
//
// To trigger this, we send items from multiple goroutines with delays around batchTimeout so the timer fires between Sends.
var mu sync.Mutex
var received []any
const numGoroutines = 5
const sendsPerGoroutine = 20
bs := NewBatchSender(func(items any) {
mu.Lock()
defer mu.Unlock()
received = append(received, items)
})
var wg sync.WaitGroup
wg.Add(numGoroutines)
for range numGoroutines {
go func() {
defer wg.Done()
for range sendsPerGoroutine {
bs.Send("item")
time.Sleep(batchTimeout + 10*time.Millisecond)
}
}()
}
wg.Wait()
bs.Close()
}