From ff386398b34860cd634a7e0b491e34bb4a4c970b Mon Sep 17 00:00:00 2001 From: Bruno Franca dos Reis <261623+bfreis@users.noreply.github.com> Date: Fri, 24 Sep 2021 15:53:53 -0700 Subject: [PATCH] fix race condition on Honeycomb.Flush() (#140) Co-authored-by: Vera Reynolds --- transmission/transmission.go | 2 +- transmission/transmission_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/transmission/transmission.go b/transmission/transmission.go index 2994dbc..ab0a0a4 100644 --- a/transmission/transmission.go +++ b/transmission/transmission.go @@ -137,13 +137,13 @@ func (h *Honeycomb) Flush() (err error) { // the old one (which has a side-effect of flushing the data) and make a new // one. We start the new one and swap it with the old one so that we minimize // the time we hold the musterLock for. - m := h.muster newMuster := h.createMuster() err = newMuster.Start() if err != nil { return err } h.musterLock.Lock() + m := h.muster h.muster = newMuster h.musterLock.Unlock() return m.Stop() diff --git a/transmission/transmission_test.go b/transmission/transmission_test.go index 21cf3de..b0d818b 100644 --- a/transmission/transmission_test.go +++ b/transmission/transmission_test.go @@ -928,6 +928,37 @@ func TestHoneycombTransmissionFlush(t *testing.T) { // Add concurrently with Flush. Before we added locks, the race detector // would detect a race here. }) + + t.Run("Flush should not race or panic if called from multiple goroutines", func(t *testing.T) { + w := new(Honeycomb) + w.MaxBatchSize = 1000 + var wg sync.WaitGroup + wg.Add(2) + + if err := w.Start(); err != nil { + t.Error("unable to start", err) + } + defer func() { + wg.Wait() + w.Stop() + }() + go func() { + defer wg.Done() + err := w.Flush() + if err != nil { + t.Error("unable to flush", err) + } + }() + go func() { + defer wg.Done() + err := w.Flush() + if err != nil { + t.Error("unable to flush", err) + } + }() + // This test makes sure that you can make concurrent calls to Flush. + // Race test used to panic here. + }) } func TestHoneycombSenderAddingResponsesBlocking(t *testing.T) {