liveBook · Manning

Goroutine leak

As explained in Go in Practice, Second Edition

A goroutine leak is a failure of a goroutine to terminate after it is no longer needed, causing it to consume system resources.

A goroutine leak occurs when a goroutine remains active after it is no longer needed, consuming resources without doing useful work. Repeatedly creating a goroutine and channel without returning or closing them can make a long-running application leaky. section 5.3.2

Prevent leaks by coordinating shutdown:

  • Make the goroutine return when its work ends. section 5.3.2
  • Close a channel only when it is safe; closing it while another goroutine sends causes a panic. section 5.3.2
  • Use a separate notification channel to tell the sending goroutine to close its channel and exit. section 5.3.2

Coordinated shutdown

A sender can select on a done channel alongside its normal work. When the receiver signals done, the sender closes the message channel and returns instead of remaining blocked or sending after closure.

How Go in Practice, Second Edition covers it

How deep it goes
Explains leak causes and shutdown coordination, including unsafe closure and sender-controlled cleanup.
Examples
Uses repeated calls, an improperly closed channel, and a done-channel shutdown listing.
What it assumes
Assumes basic goroutines and channels while clarifying channel closure and receiver-sender coordination.
What you can do after
Diagnose resource leaks and implement coordinated goroutine shutdown with channels.
How it connects
Connects goroutine leaks with channels, channel closure, goroutine termination, and memory leaks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.