user13505500
user13505500

Reputation:

Ticker without ticker.Stop()

GoDoc says

Stop the ticker to release associated resources

However, a stack frame is destroyed and GC collect allocated resource on that frame. If we don't do ticker.Stop(), what about the allocated resource related to ticker? Like following code:

func startReloader(duration time.Duration, reloader an_sync.IReloader, datasource string) {
     ticker := time.NewTicker(duration / 10)
     <-ticker.C
     //dosomething here
 }
 //here is ticker struct
 type Ticker struct {
     C <-chan Time // The channel on which the ticks are delivered.
     r runtimeTimer
 }

Do we still have a memory leak here?

Upvotes: 0

Views: 2368

Answers (1)

icza
icza

Reputation: 418565

time.NewTicker() may start new, background goroutines to manage the timers, which have their own stacks independent from the stack of your goroutine. So yes, if you don't call Ticker.Stop(), resources may not be freed even when your goroutine ends and you don't have any reference to the ticker anymore.

If you don't need a ticker anymore, do call its Ticker.Stop() as the doc suggests.

Upvotes: 2

Related Questions