Runtime and memory · 3 MIN READ
What the garbage collector can and cannot free
Follow references from roots and distinguish unreachable objects from unwanted live data.
Garbage collection reclaims memory that the runtime determines is no longer reachable. It does not know that an application has lost interest in a cache entry, nor does it close a forgotten network connection on a useful schedule. Ownership still matters.
Think in reference paths
Imagine a global cache holding a pointer to an order, which points to a large receipt buffer. As long as a live reference path reaches the buffer, it is not garbage. Removing one local reference is insufficient when the cache still holds another.
type Order struct { Receipt []byte }
var cache = map[string]*Order{}
func remember(id string, receipt []byte) {
cache[id] = &Order{Receipt: receipt}
}
// These helpers assume a single owner of cache.
func forget(id string) {
delete(cache, id)
}Delete removes this map entry, not every possible reference to the order. Concurrent access to the map would require synchronization. The example focuses only on the reference graph.
Collection is not immediate destruction
An unreachable allocation becomes eligible for reclamation; there is no promise that the operating system immediately receives the same amount of memory. Runtime-managed free space can be reused. RSS, live heap and total allocated bytes answer different questions, so compare like with like when diagnosing growth.
Resources need explicit lifetime management
Close files and response bodies, stop owned background workers, and bound caches according to their contracts. A tracing collector can collect unreachable cycles, but it cannot make an indefinitely blocked goroutine release the values it still reaches. Avoid finalizers as normal cleanup: their timing does not establish a reliable resource protocol.
TAKE THIS WITH YOU
The GC answers reachability, not business usefulness. Remove unwanted references and close resources explicitly; then measure the correct memory metric.
Check your understanding
Which statement is correct about a cached reachable object?
Go to the source
Progress stays in this browser. No account needed.