0

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?

3
  • "Do we still have a memory leak here?" Technically it is a resource leak. Whether memory is part of the leaked resource is unspecified (but yes). In the most case the documentation is correct and you should just do what the documentation says (even if you think the documentation is wrong as it is more likely that the documentation is correct and you are wrong).
    – Volker
    Jan 29, 2021 at 9:17
  • @Volker Thanks, I do stop the timer with defer every time I create a timer. It's just I don't get it why destroyed the stack frame can't release allocated resources. I will do it. Thanks again
    – user13505500
    Jan 29, 2021 at 9:29
  • You are talking about a stack frame which is a concept that doesn't exist at all on the language level. The language spec doesn't even contain the word "stack". This stack-stuff is an implementation detail of each compiler. There might be go compilers which do not use a stack at all. So destroying a nonexisting stack frame would not release anything in these compilers.
    – Volker
    Jan 29, 2021 at 9:59

1 Answer 1

2

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.

1
  • Thanks, I didn't realize that there is a background goroutine out there. I get it now.
    – user13505500
    Jan 29, 2021 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy