Golang / GoLang Basics Interview Questions
What is a goroutine leak and what is the idiomatic way to prevent one?
A goroutine leak occurs when a goroutine is started but never terminates — it stays blocked forever waiting on a channel, mutex, or network call that will never complete. Goroutines are cheap but not free: leaked goroutines accumulate over time and eventually exhaust memory in long-running services.
// LEAK — goroutine blocks forever; nobody ever sends to ch
func leaky() {
ch := make(chan int)
go func() {
v := <-ch // blocks indefinitely
fmt.Println(v)
}()
// function returns — goroutine is stuck forever!
}
// FIX: pass a context and select on ctx.Done()
func safe(ctx context.Context, ch <-chan int) {
go func() {
select {
case v := <-ch:
fmt.Println(v)
case <-ctx.Done(): // goroutine exits cleanly when cancelled
return
}
}()
}
// FIX: close the channel to unblock receivers
func producer() <-chan int {
ch := make(chan int)
go func() {
defer close(ch) // close signals: no more values
for _, v := range data {
ch <- v
}
}()
return ch
}
// Detect leaks in tests:
// defer goleak.VerifyNone(t) — fails test if goroutines remain
// runtime.NumGoroutine() — watch for steady growth
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
