Golang / GoLang Concurrency Mastery Interview Questions
How do you write tests that detect goroutine leaks automatically?
Goroutine leaks are among the hardest production bugs to diagnose — they accumulate invisibly. Catching them at test time is far more effective than debugging production memory growth.
import (
"testing"
"runtime"
"time"
"go.uber.org/goleak"
)
// Method 1: goleak — recommended, most accurate
func TestNoLeak(t *testing.T) {
defer goleak.VerifyNone(t) // fails if goroutines remain after test
svc := NewService()
svc.Start()
// ... exercise the service ...
svc.Stop() // if Stop() leaks a goroutine, goleak catches it
}
// goleak with TestMain — check all tests in the package
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m,
goleak.IgnoreTopFunction("database/sql.(*DB).connectionOpener"),
)
}
// Method 2: manual count check (simpler, less precise)
func TestGoroutineCount(t *testing.T) {
before := runtime.NumGoroutine()
svc := NewService()
svc.Start()
svc.Stop()
time.Sleep(100 * time.Millisecond) // let goroutines exit
runtime.Gosched()
after := runtime.NumGoroutine()
if after > before {
buf := make([]byte, 1<<20)
n := runtime.Stack(buf, true)
t.Errorf("goroutine leak: %d before, %d after\n%s",
before, after, buf[:n])
}
}
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...
