From 508bb17edd04479622fad263cd702deac1c49157 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Wed, 14 Feb 2024 20:36:47 -0500 Subject: time: garbage collect unstopped Tickers and Timers From the beginning of Go, the time package has had a gotcha: if you use a select on <-time.After(1*time.Minute), even if the select finishes immediately because some other case is ready, the underlying timer from time.After keeps running until the minute is over. This pins the timer in the timer heap, which keeps it from being garbage collected and in extreme cases also slows down timer operations. The lack of garbage collection is the more important problem. The docs for After warn against this scenario and suggest using NewTimer with a call to Stop after the select instead, purely to work around this garbage collection problem. Oddly, the docs for NewTimer and NewTicker do not mention this problem, but they have the same issue: they cannot be collected until either they are Stopped or, in the case of Timer, the timer expires. (Tickers repeat, so they never expire.) People have built up a shared knowledge that timers and tickers need to defer t.Stop even though the docs do not mention this (it is somewhat implied by the After docs). This CL fixes the garbage collection problem, so that a timer that is unreferenced can be GC'ed immediately, even if it is still running. The approach is to only insert the timer into the heap when some channel operation is blocked on it; the last channel operation to stop using the timer takes it back out of the heap. When a timer's channel is no longer referenced, there are no channel operations blocked on it, so it's not in the heap, so it can be GC'ed immediately. This CL adds an undocumented GODEBUG asynctimerchan=1 that will disable the change. The documentation happens in the CL 568341. Fixes #8898. Fixes #61542. Change-Id: Ieb303b6de1fb3527d3256135151a9e983f3c27e6 Reviewed-on: https://go-review.googlesource.com/c/go/+/512355 Reviewed-by: Austin Clements LUCI-TryBot-Result: Go LUCI Auto-Submit: Russ Cox --- doc/godebug.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'doc') diff --git a/doc/godebug.md b/doc/godebug.md index 2b8852a7ec..515c40cd39 100644 --- a/doc/godebug.md +++ b/doc/godebug.md @@ -128,6 +128,8 @@ and the [go command documentation](/cmd/go#hdr-Build_and_test_caching). ### Go 1.23 +TODO: `asynctimerchan` setting. + Go 1.23 changed the mode bits reported by [`os.Lstat`](/pkg/os#Lstat) and [`os.Stat`](/pkg/os#Stat) for reparse points, which can be controlled with the `winsymlink` setting. As of Go 1.23 (`winsymlink=1`), mount points no longer have [`os.ModeSymlink`](/pkg/os#ModeSymlink) -- cgit v1.2.3-54-g00ecf