From 48c73d6a34add5160c203a201ed38250d736f362 Mon Sep 17 00:00:00 2001 From: Douglas De Toni Machado Date: Thu, 4 Jun 2020 06:04:04 -0300 Subject: [PATCH] Fix mem leak on UDP connections --- pkg/udp/conn.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/pkg/udp/conn.go b/pkg/udp/conn.go index 0fec8ce04..516212ec2 100644 --- a/pkg/udp/conn.go +++ b/pkg/udp/conn.go @@ -177,7 +177,7 @@ func (l *Listener) newConn(rAddr net.Addr) *Conn { readCh: make(chan []byte), sizeCh: make(chan int), doneCh: make(chan struct{}), - ticker: time.NewTicker(timeoutTicker), + timeout: timeoutTicker, } } @@ -194,7 +194,7 @@ type Conn struct { muActivity sync.RWMutex lastActivity time.Time // the last time the session saw either read or write activity - ticker *time.Ticker // for timeouts + timeout time.Duration // for timeouts doneOnce sync.Once doneCh chan struct{} } @@ -204,12 +204,15 @@ type Conn struct { // that is to say it waits on readCh to receive the slice of bytes that the Read operation wants to read onto. // The Read operation receives the signal that the data has been written to the slice of bytes through the sizeCh. func (c *Conn) readLoop() { + ticker := time.NewTicker(c.timeout) + defer ticker.Stop() + for { if len(c.msgs) == 0 { select { case msg := <-c.receiveCh: c.msgs = append(c.msgs, msg) - case <-c.ticker.C: + case <-ticker.C: c.muActivity.RLock() deadline := c.lastActivity.Add(connTimeout) c.muActivity.RUnlock() @@ -229,7 +232,7 @@ func (c *Conn) readLoop() { c.sizeCh <- n case msg := <-c.receiveCh: c.msgs = append(c.msgs, msg) - case <-c.ticker.C: + case <-ticker.C: c.muActivity.RLock() deadline := c.lastActivity.Add(connTimeout) c.muActivity.RUnlock() @@ -281,6 +284,5 @@ func (c *Conn) Close() error { c.listener.mu.Lock() defer c.listener.mu.Unlock() delete(c.listener.conns, c.rAddr.String()) - c.ticker.Stop() return nil }