go resource_error ai_generated true

fatal error: runtime: out of memory (timer channel leak)

ID: go/goroutine-timer-channel-leak

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Creating many time.Timer or time.Ticker without stopping them, causing goroutine and channel leaks that exhaust memory.

generic

中文

创建大量 time.Timer 或 time.Ticker 而不停止它们,导致协程和通道泄漏,耗尽内存。

Workarounds

  1. 95% success Always stop timers after use with defer.
    timer := time.NewTimer(1 * time.Second)
    defer timer.Stop()
    select {
    case <-timer.C:
        // do something
    }
  2. 90% success Use time.NewTicker and stop it when done.
    ticker := time.NewTicker(1 * time.Second)
    defer ticker.Stop()
    for range ticker.C {
        // periodic work
        if condition {
            break
        }
    }

Dead Ends

Common approaches that don't work:

  1. Using time.After in a loop without resetting. 90% fail

    Each call to time.After creates a new timer; if not stopped, they accumulate.

  2. Assuming timers are garbage collected after firing. 80% fail

    Timers are not GC'd until they fire or are stopped; if not stopped, they remain in memory.