Section 10
Goroutines
A goroutine is a function running concurrently with others in the same process. Start one with go functionCall(). The Go runtime schedules goroutines across OS threads automatically.
Thread vs Goroutine
☕ Java Thread
◎ Go Goroutine
☕ ~1MB initial stack
◎ ~2KB initial stack, grows on demand
☕ Managed by OS
◎ Managed by Go runtime scheduler
☕ ~10K threads before OOM
◎ Millions of goroutines in production
☕ new Thread(() -> ...).start()
◎ go func() { ... }()
☕ Future/CompletableFuture for results
◎ Channels for results (next section)
☕ Thread pool (ExecutorService)
◎ No pool needed — goroutines are cheap
Starting a goroutine
☕ Java — Thread or ExecutorService
◎ Go — go keyword
Goroutine lifecycle
Four states
Runnable — created with
Running — executing on an OS thread right now
Waiting — blocked on I/O, sleep, or synchronisation. Its OS thread is freed for other goroutines
Dead — function returned. Stack reclaimed. No explicit join.
The scheduler runs GOMAXPROCS OS threads (= CPU cores by default). When a goroutine blocks, its thread immediately picks up another runnable goroutine. This is why Go can handle thousands of concurrent I/O operations with only a handful of threads.
go, waiting for a thread slotRunning — executing on an OS thread right now
Waiting — blocked on I/O, sleep, or synchronisation. Its OS thread is freed for other goroutines
Dead — function returned. Stack reclaimed. No explicit join.
The scheduler runs GOMAXPROCS OS threads (= CPU cores by default). When a goroutine blocks, its thread immediately picks up another runnable goroutine. This is why Go can handle thousands of concurrent I/O operations with only a handful of threads.
go func() — anonymous goroutine, fully explained
every part of 'go func() { ... }()' explained
The closure capture bug — very common mistake
loop variable capture — wrong vs right
WaitGroup — waiting for goroutines to finish
☕ Java — Future or CountDownLatch
◎ Go — sync.WaitGroup
!
wg.Add(1) must be called BEFORE launching the goroutine, in the parent goroutine. If you call it inside the goroutine, wg.Wait() may return before Add() even executes.Debugging goroutines
runtime inspection — how many are running?