Goroutine Leaks
Start with Goroutine Leaks
In this lesson, explore goroutine leaks through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of goroutine leaks.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A goroutine leak occurs when a task stays blocked or alive after its work is no longer useful. Common causes include channel sends with no receiver and loops that never observe cancellation.
Give each spawned goroutine a stopping condition and arrange for its owner to cancel or join it.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"context"
"fmt"
"sync"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); <-ctx.Done() }()
cancel()
wg.Wait()
fmt.Println("Worker stopped")
}
Output
Worker stoppedTrace what the program does
Cancellation closes Done. The waiting goroutine exits and signals the WaitGroup, so main can report that no worker was left waiting.
Avoid common mistakes
- A timeout at the receiver alone may leave the sender blocked forever.
- Context cancellation only works if the goroutine checks it.
Try it yourself
Extend the worker to select between incoming jobs and context cancellation; stop it after one job.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Goroutine Leaks in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.