What is Goroutine Leak in Go: Explanation and Example
goroutine leak in Go happens when a goroutine keeps running but is never stopped or cleaned up, causing wasted memory and resources. It usually occurs when a goroutine waits forever on a channel or condition that never happens.How It Works
Imagine you start a small worker in your program to do a task in the background. This worker is a goroutine. If this worker never finishes or stops because it is waiting for something that never comes, it keeps using memory and CPU. This is called a goroutine leak.
It is like leaving a faucet running in your house without using the water. The water keeps flowing and wastes resources. Similarly, a leaked goroutine keeps running and wastes your program's resources.
Goroutine leaks often happen when a goroutine waits on a channel or a signal that never arrives, so it never exits. Over time, many leaked goroutines can slow down or crash your program.
Example
This example shows a goroutine that waits forever on a channel that never receives a value, causing a goroutine leak.
package main import ( "fmt" "time" ) func leakyGoroutine(ch chan int) { // This goroutine waits forever for a value on ch <-ch fmt.Println("Received value, exiting goroutine") } func main() { ch := make(chan int) for i := 0; i < 3; i++ { go leakyGoroutine(ch) } fmt.Println("Started 3 goroutines that leak") // Sleep to show program running time.Sleep(2 * time.Second) fmt.Println("Main function ends, but goroutines are still waiting") }
When to Use
Understanding goroutine leaks is important when you write programs that use many goroutines, such as servers, concurrent workers, or background tasks. You want to avoid leaks to keep your program fast and stable.
Use this knowledge to carefully design goroutines so they can stop when no longer needed. For example, use context.Context to cancel goroutines or close channels properly.
Real-world cases include web servers handling many requests or programs processing streams of data where goroutines must exit cleanly after work is done.
Key Points
- A goroutine leak happens when a goroutine never stops and wastes resources.
- It often occurs when waiting on channels or signals that never arrive.
- Leaked goroutines can slow down or crash your program over time.
- Use cancellation techniques like
context.Contextto avoid leaks.