ProgramGuru

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.

Visual explanation for goroutine leaksEvery goroutine should have an owner and exit condition.Start background taskStep 1Owner cancelsStep 2Worker observes DoneStep 3Join and exitStep 4Every goroutine should have an owner and exit condition.
Every goroutine should have an owner and exit condition.

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 stopped

Trace 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 is a reliable way to prevent a worker from waiting forever?
Choose one answer. You can try again.

Answer and explanation

Provide a cancellation path and join it

Correct. Cancellation closes Done.

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.

    Next lesson: Concurrency Best Practices →