Golang / GoLang Concurrency Mastery Interview Questions
What causes goroutine leaks and how do you prevent and detect them?
A goroutine leak occurs when a goroutine starts but never terminates — it blocks indefinitely waiting on a channel, lock, or I/O that will never complete. Leaked goroutines accumulate over time, consuming memory and potentially holding references that prevent GC, causing steady memory growth until OOM.
// LEAK 1: nobody ever sends to ch â goroutine parks forever func leak1() { ch := make(chan int) go func() { v := <-ch // blocks; function returns; nobody sends â leaked process(v) }() } // FIX: use context for cancellation func fixed1(ctx context.Context) { ch := make(chan int) go func() { select { case v := <-ch: process(v) case <-ctx.Done(): return } }() } // LEAK 2: jobs channel never closed func leak2() { jobs := make(chan Job) go func() { for job := range jobs { process(job) } // waits forever }() // forgot close(jobs) â goroutine never exits } // LEAK 3: time.Ticker never stopped func leak3() { ticker := time.NewTicker(time.Second) go func() { for range ticker.C { doWork() } // runs forever }() // forgot ticker.Stop() â goroutine and channel leaked } // DETECTION: // runtime.NumGoroutine() â watch for steady growth // /debug/pprof/goroutine?debug=2 â full goroutine stack traces // goleak library in tests: // import "go.uber.org/goleak" // defer goleak.VerifyNone(t) // fails test if goroutines leak
More Related questions...