Sending on a Go Channel You Never Close Is Fine, Until It Isn't
Plenty of Go code never calls close on its channels and is perfectly correct. Other code hangs forever because of exactly the same omission. Which camp you land in depends on who is waiting on the channel.
Close is a message, not a free()
A channel is an ordinary heap object. When nothing can reach it any more, the garbage collector reclaims it, closed or not. There's no file descriptor or OS handle behind it, so nothing needs releasing.
Closing a channel does one thing: it tells receivers that no more values are coming. If no receiver needs that news, skipping it costs you nothing:
func square(n int) int {
ch := make(chan int, 1)
go func() { ch <- n * n }()
return <-ch
}
There's one value, one receive and no loop, so adding close(ch) here would just be noise.
Where it breaks: a receiver that waits for the end
The first way this goes wrong is for range over a channel. The loop only ends when the channel is closed and drained, so a sender that forgets to close leaves the receiver waiting for a "that's all" it will never get:
func main() {
ch := make(chan int)
go func() {
for i := 0; i < 3; i++ {
ch <- i
}
}()
for v := range ch {
fmt.Println(v)
}
}
This prints 0, 1, 2 and then dies with fatal error: all goroutines are asleep - deadlock!. The fix is one line, defer close(ch), in the goroutine that does the sending.
The runtime only noticed because every goroutine was stuck. In a real server, with HTTP handlers and timers alive, the same bug produces no crash and no message, just a goroutine that never returns.
Quick detour: why a blocked goroutine is never collected
Hang on, if the GC collects unreachable channels, why doesn't it collect a channel nobody else references? Because the goroutine blocked on it isn't garbage. A goroutine's stack is a root, and that stack references the channel, so both stay alive. The collector won't reap a blocked goroutine, however hopeless its situation, which is why leaks like this just grow until something notices the memory.
The mirror image: a sender with no receiver
Here closing wouldn't help at all, because the problem is on the sending side:
func fastest(urls []string) string {
ch := make(chan string)
for _, u := range urls {
go func() { ch <- fetch(u) }()
}
return <-ch
}
The function takes the first answer and returns. Every other goroutine then blocks on ch <- for ever, because the unbuffered channel has no receiver left. Call this per request and you leak len(urls) - 1 goroutines each time.
Closing can't fix this, because sending on a closed channel panics. Give the sends somewhere to land instead:
ch := make(chan string, len(urls))
Now every sender completes, drops its value into the buffer and exits. When fastest returns, the channel and its leftover values become unreachable and the GC takes them. The channel is still never closed, and the code is now correct.
A quick way to decide
- Does any receiver loop with
range, or wait for the "ok" value fromv, ok := <-ch? Then something must close it. - Does a receiver exit early (first result wins, context cancelled, error)? Then senders need a buffer or a
selectonctx.Done(). - Is it exactly one send and one receive? Do not bother closing.
With several senders, none of them can safely close the channel on its own. Count them with a sync.WaitGroup and close from one extra goroutine that waits:
go func() {
wg.Wait()
close(out)
}()
The receiver can then range over out and finish cleanly.
Finding the leak when you have one
Blocked goroutines are easy to spot in a goroutine dump. Hit /debug/pprof/goroutine?debug=2 if you have net/http/pprof enabled, and look for many identical stacks parked in chan send or chan receive with a long wait time. The line number in the stack points at the exact send or receive that nobody will ever match.
The rule I keep is short: close when a receiver needs to know the stream ended, and only from the sender. For everything else, make sure no goroutine can be left holding the other end.