Weak pointers and cleanups

suggest change

Go's garbage collector frees memory once nothing can reach it. Most programs never need to know when that happens. Two situations do:

For years the only tool was runtime.SetFinalizer. Go 1.24 added two better ones: runtime.AddCleanup runs a function after an object becomes unreachable, and the weak package provides weak.Pointer[T], a pointer the GC ignores when it decides what is alive.

This article covers:

For how the collector itself works, see Memory, escape analysis, and garbage collection.

A note on runtime.GC in examples

The examples call runtime.GC() to force a collection, then sleep for a few milliseconds because cleanups run on a separate goroutine. That's fine for a demonstration and wrong in a real program. A real program can't know when, or whether, a cleanup will run. The runtime only promises that it won't run while the object is reachable. It may run much later, and it isn't guaranteed to run before the program exits.

So cleanups and weak pointers are for releasing resources and memory you'd otherwise leak. Never make the correctness of a program depend on them.

The problems with SetFinalizer

runtime.SetFinalizer(obj, f) arranges for f(obj) to be called when obj becomes unreachable:

package main

import (
	"fmt"
	"runtime"
	"time"
)

type Resource struct {
	name string
}

var saved *Resource

func main() {
	r := &Resource{name: "db-conn"}
	runtime.SetFinalizer(r, func(r *Resource) {
		fmt.Println("finalizer for", r.name)
		saved = r // resurrection: r is reachable again
	})
	r = nil

	runtime.GC()
	time.Sleep(10 * time.Millisecond) // finalizers run on a separate goroutine
	fmt.Println("resurrected:", saved.name)

	saved = nil
	runtime.GC()
	time.Sleep(10 * time.Millisecond)
	fmt.Println("done; the finalizer ran only once")
}
finalizer for db-conn
resurrected: db-conn
done; the finalizer ran only once

The finalizer receives the object itself, and that causes most of the trouble:

The cycle problem is easy to hit by accident. Here every pair of nodes is a cycle and each pair holds 2 MB:

package main

import (
	"fmt"
	"runtime"
	"time"
)

type Node struct {
	name string
	next *Node
	buf  [1 << 20]byte // 1 MB, so the leak is visible
}

func heapMB() uint64 {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	return m.HeapAlloc >> 20
}

func makePair(withFinalizer bool) {
	a := &Node{name: "a"}
	b := &Node{name: "b", next: a}
	a.next = b // cycle: a -> b -> a
	if withFinalizer {
		runtime.SetFinalizer(a, func(n *Node) { fmt.Println("finalized", n.name) })
	}
}

func main() {
	for range 50 {
		makePair(false)
	}
	runtime.GC()
	fmt.Println("cycles without finalizer, heap MB:", heapMB())

	for range 50 {
		makePair(true)
	}
	runtime.GC()
	time.Sleep(10 * time.Millisecond)
	runtime.GC()
	fmt.Println("cycles with finalizer, heap MB:", heapMB())
}
cycles without finalizer, heap MB: 0
cycles with finalizer, heap MB: 101

Without finalizers, the GC frees the unreachable cycles. With a finalizer on one node of each pair, all 100 MB stays allocated and finalized is never printed. The documentation of SetFinalizer now says that new code should use AddCleanup instead.

runtime.AddCleanup

func AddCleanup[T, S any](ptr *T, cleanup func(S), arg S) Cleanup

Some time after ptr becomes unreachable, the runtime calls cleanup(arg) on a separate goroutine. The difference from a finalizer is that the cleanup doesn't receive the object. It receives arg, which should be just the thing that needs releasing: a file descriptor, a C pointer, a map key. Because nothing hands the object back to your code, it can't be resurrected, it can be freed right away, and cycles are collected normally.

A typical use is a Go type that wraps a resource from somewhere else. Here a pretend OS API hands out integer handles:

package main

import (
	"fmt"
	"runtime"
	"time"
)

// A pretend OS API that hands out integer handles.
var nextHandle = 100

func osOpen() int   { nextHandle++; return nextHandle }
func osClose(h int) { fmt.Println("closed handle", h) }

// File wraps a handle. The cleanup is attached to *File,
// but it only needs the handle, not the File.
type File struct {
	handle  int
	cleanup runtime.Cleanup
}

func Open() *File {
	f := &File{handle: osOpen()}
	f.cleanup = runtime.AddCleanup(f, osClose, f.handle)
	return f
}

// Close releases the handle deterministically and cancels the cleanup,
// so the handle isn't closed twice.
func (f *File) Close() {
	f.cleanup.Stop()
	osClose(f.handle)
}

func main() {
	f1 := Open()
	f1.Close()

	_ = Open() // leaked: nobody calls Close
	_ = Open()

	runtime.GC()
	time.Sleep(10 * time.Millisecond) // cleanups run on another goroutine
	fmt.Println("end of main")
}
closed handle 101
closed handle 102
closed handle 103
end of main

Handle 101 was closed by Close. Handles 102 and 103 were leaked and closed by their cleanups. There's no specified order in which cleanups run, so 103 may come before 102.

This is the pattern to follow:

Stop has no effect if the cleanup has already been queued because the object became unreachable. Calling it from a method on the object, as Close does, keeps the object reachable during the call, so that can't happen here.

Compared with SetFinalizer, AddCleanup also lifts the other restrictions. An object can have any number of cleanups, ptr may point into the middle of an object, and cleanups can run concurrently with one another:

package main

import (
	"fmt"
	"runtime"
	"time"
)

type Conn struct {
	addr  string
	stats [4]int
}

func main() {
	c := &Conn{addr: "10.0.0.1:5432"}
	say := func(msg string) { fmt.Println(msg) }

	// Several cleanups on one object, and one on a field:
	// all of them run once the whole Conn is unreachable.
	runtime.AddCleanup(c, say, "close socket")
	runtime.AddCleanup(c, say, "unregister from pool")
	runtime.AddCleanup(&c.stats, say, "flush stats")

	c = nil
	runtime.GC()
	time.Sleep(10 * time.Millisecond)
}
unregister from pool
close socket
flush stats

Because cleanups may run in parallel, a cleanup that touches shared state needs a mutex. A cleanup that takes a long time should start its own goroutine, so it doesn't hold up the others.

The cleanup must not reference the object

If ptr can be reached from cleanup or from arg, the object is always reachable: the runtime holds on to the cleanup, and the cleanup holds on to the object. It's never collected and the cleanup never runs. The runtime catches the two simplest forms of this mistake and panics:

f := &File{handle: 1}
// WRONG: the closure captures f
runtime.AddCleanup(f, func(int) { osClose(f.handle) }, 0)
panic: runtime.AddCleanup: cleanup function closes over ptr, cleanup will never run
g := &File{handle: 2}
// WRONG: arg is the object itself
runtime.AddCleanup(g, func(g *File) { osClose(g.handle) }, g)
panic: runtime.AddCleanup: ptr is equal to arg, cleanup will never run

An indirect reference isn't detected and silently leaks:

type Owner struct {
	f *File
}

f := &File{handle: 3}
o := &Owner{f: f}
// WRONG: f is reachable through o
runtime.AddCleanup(f, func(o *Owner) { osClose(o.f.handle) }, o)

The same happens when arg is a struct that contains a pointer to the object, or when the closure captures such a struct.

The fix is always to pass the smallest value the cleanup needs: the handle, not the File; the C pointer, not the wrapper.

To find this kind of bug, run the program with GODEBUG=checkfinalizers=1 (Go 1.25+). During each GC it checks whether an object with a cleanup or finalizer is reachable from its own cleanup, and crashes with a report pointing at the AddCleanup call:

$ GODEBUG=checkfinalizers=1 go run .
WARNING: LIKELY CLEANUP/FINALIZER ISSUES

Value of type main.File at 0x2b9396d8c0f0
  is reachable from cleanup or cleanup argument

Has cleanup at 0x2234d0f0400
  main.main.func2()
      C:/work/cleanup/main.go:28 +0x0
created at:
  main.main()
      C:/work/cleanup/main.go:33 +0x1b3

fatal error: detected possible issues with cleanups and/or finalizers
...

It slows down every GC, so use it in tests and during development, not in production.

Objects can die earlier than you think

The GC considers an object unreachable after the last point where the code uses it, not at the end of the enclosing function. If a method copies the handle into a local variable and then never touches the receiver again, the object can be collected, and its cleanup can close the handle, while the method is still using that handle:

package main

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)

// A pretend OS API that tracks open handles.
var (
	mu     sync.Mutex
	open   = map[int]bool{}
	nextID = 0
)

func osOpen() int {
	mu.Lock()
	defer mu.Unlock()
	nextID++
	open[nextID] = true
	return nextID
}

func osClose(h int) {
	mu.Lock()
	defer mu.Unlock()
	delete(open, h)
	fmt.Println("closed handle", h)
}

func osRead(h int) {
	mu.Lock()
	defer mu.Unlock()
	if !open[h] {
		fmt.Println("ERROR: read from closed handle", h)
		return
	}
	fmt.Println("read from handle", h)
}

type File struct {
	name   string
	handle int
}

func Open() *File {
	f := &File{name: "data.bin", handle: osOpen()}
	runtime.AddCleanup(f, osClose, f.handle)
	return f
}

// ReadBuggy: f may be collected while h is still in use.
func (f *File) ReadBuggy() {
	h := f.handle // the last use of f
	runtime.GC()  // simulate a GC happening at this point
	time.Sleep(10 * time.Millisecond)
	osRead(h)
}

func (f *File) Read() {
	h := f.handle
	runtime.GC()
	time.Sleep(10 * time.Millisecond)
	osRead(h)
	runtime.KeepAlive(f) // f stays reachable until here
}

func main() {
	fmt.Println("without KeepAlive:")
	Open().ReadBuggy()

	fmt.Println("with KeepAlive:")
	Open().Read()
}
without KeepAlive:
closed handle 1
ERROR: read from closed handle 1
with KeepAlive:
read from handle 2

runtime.KeepAlive(x) does nothing at run time, but it counts as a use of x, so x is reachable at least up to that call. Put it after the last operation that needs the resource. This matters most in wrappers around system calls and C functions, where the Go code passes a raw handle or pointer and nothing else refers to the wrapper.

The example has a name string field for a reason. With only handle int, File would be an 8-byte object without pointers. The runtime packs such tiny objects (16 bytes or less, no pointers) together into one memory block, and the block is freed only when every object in it is dead. The bug then doesn't show up in this small program, and the cleanup may never run at all. Don't rely on cleanups or weak pointers for tiny pointer-free values, or for zero-size types.

Weak pointers

A weak.Pointer[T] refers to an object without keeping it alive. If the only references left to an object are weak ones, the GC frees it.

package main

import (
	"fmt"
	"runtime"
	"weak"
)

type Image struct {
	name   string
	pixels []byte
}

func main() {
	img := &Image{name: "logo.png", pixels: make([]byte, 1<<20)}
	wp := weak.Make(img)
	wp2 := weak.Make(img)

	// While img is reachable, Value returns the original pointer.
	if p := wp.Value(); p != nil {
		fmt.Println("alive:", p.name, p == img)
	}

	runtime.GC()
	fmt.Println("after GC, still used:", wp.Value() != nil)
	runtime.KeepAlive(img) // img is reachable up to this point

	// Nothing uses img after KeepAlive, so this GC can reclaim it.
	runtime.GC()
	fmt.Println("after GC, unused:", wp.Value() == nil)

	// Weak pointers made from the same pointer compare equal,
	// even after the object is gone.
	fmt.Println("wp == wp2:", wp == wp2)

	var zero weak.Pointer[Image]
	fmt.Println("zero value:", zero.Value(), zero == weak.Make[Image](nil))
}
alive: logo.png true
after GC, still used: true
after GC, unused: true
wp == wp2: true
zero value: <nil> true

Things to know about weak pointers:

The standard library uses weak pointers to implement the unique package (see Interning values with unique), which interns values: unique.Make returns the same handle for equal values, and the canonical copy is freed when no handle refers to it anymore.

A cache that doesn't keep values alive

A typical cache holds strong references, so a cached value stays in memory until the cache evicts it, even if nothing else in the program is using it. Sometimes you want the opposite. The cache only finds a value that is still alive somewhere else, so that two parts of the program share one copy of a parsed template or a decoded image, and the value goes away when they're done with it.

A map from keys to weak pointers does that. A cleanup on each value removes its map entry once the value is collected, so the map doesn't fill up with dead entries:

package main

import (
	"fmt"
	"runtime"
	"sync"
	"time"
	"weak"
)

// WeakCache maps keys to values without keeping the values alive.
// A value stays in the cache as long as some other part of the
// program holds a pointer to it.
type WeakCache[K comparable, V any] struct {
	mu sync.Mutex
	m  map[K]weak.Pointer[V]
}

func NewWeakCache[K comparable, V any]() *WeakCache[K, V] {
	return &WeakCache[K, V]{m: map[K]weak.Pointer[V]{}}
}

func (c *WeakCache[K, V]) Get(key K, load func(K) *V) *V {
	c.mu.Lock()
	defer c.mu.Unlock()

	if wp, ok := c.m[key]; ok {
		if v := wp.Value(); v != nil {
			return v // still alive
		}
	}

	v := load(key)
	wp := weak.Make(v)
	c.m[key] = wp

	// When v is collected, remove its entry. The cleanup gets the key
	// and the weak pointer, never v itself.
	runtime.AddCleanup(v, func(key K) {
		c.mu.Lock()
		defer c.mu.Unlock()
		// The entry may have been replaced by a newer value
		// after v died; only delete our own entry.
		if c.m[key] == wp {
			delete(c.m, key)
		}
	}, key)
	return v
}

func (c *WeakCache[K, V]) Len() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return len(c.m)
}

type Template struct {
	name string
	body []byte
}

func loadTemplate(name string) *Template {
	fmt.Println("  loading", name)
	return &Template{name: name, body: make([]byte, 64<<10)}
}

func main() {
	cache := NewWeakCache[string, Template]()

	fmt.Println("first use:")
	home := cache.Get("home.html", loadTemplate)
	cache.Get("about.html", loadTemplate)
	cache.Get("blog.html", loadTemplate)
	fmt.Println("entries:", cache.Len())

	fmt.Println("second use:")
	cache.Get("home.html", loadTemplate) // hit
	cache.Get("about.html", loadTemplate)
	fmt.Println("entries:", cache.Len())

	runtime.GC()
	time.Sleep(10 * time.Millisecond) // let the cleanups run
	fmt.Println("after GC, entries:", cache.Len())

	fmt.Println("third use:")
	cache.Get("home.html", loadTemplate) // still alive: we hold home
	cache.Get("blog.html", loadTemplate) // was collected, reloaded
	runtime.KeepAlive(home)
}
first use:
  loading home.html
  loading about.html
  loading blog.html
entries: 3
second use:
entries: 3
after GC, entries: 1
third use:
  loading blog.html

Before the GC, all three templates are found without reloading because no collection has happened yet. After the GC, only home.html survives, because main still holds home. The other two entries were removed by their cleanups.

Details that make this correct:

Keep in mind that a purely weak cache empties on every GC cycle, possibly every few milliseconds in a busy program. It shares values that are in use; it doesn't keep popular values around. If you want that, combine it with a small LRU of strong references, or use a regular cache with a size limit and TTL like the ones in Caching. For reusing temporary buffers, sync.Pool is the right tool; it's also emptied by the GC, but it doesn't look values up by key.

Freeing C memory and OS resources

Memory allocated by C code is invisible to the Go GC. A Go wrapper that owns such memory is the textbook use of AddCleanup. See Calling C from Go with cgo for cgo basics.

package main

// #include <stdlib.h>
import "C"

import (
	"fmt"
	"runtime"
	"time"
	"unsafe"
)

// Buffer owns memory allocated by C. The Go GC doesn't know about
// that memory, so we must free it ourselves.
type Buffer struct {
	ptr     unsafe.Pointer
	size    int
	cleanup runtime.Cleanup
}

func freeC(p unsafe.Pointer) {
	fmt.Printf("free %p\n", p)
	C.free(p)
}

func NewBuffer(size int) *Buffer {
	p := C.malloc(C.size_t(size))
	fmt.Printf("malloc %d bytes at %p\n", size, p)
	b := &Buffer{ptr: p, size: size}
	// The cleanup gets the C pointer, not b.
	b.cleanup = runtime.AddCleanup(b, freeC, p)
	return b
}

// Free releases the memory now. The cleanup is only a safety net
// for buffers that somebody forgot to free.
func (b *Buffer) Free() {
	if b.ptr == nil {
		return
	}
	b.cleanup.Stop()
	freeC(b.ptr)
	b.ptr = nil
}

func (b *Buffer) Bytes() []byte {
	return unsafe.Slice((*byte)(b.ptr), b.size)
}

func main() {
	b := NewBuffer(1024)
	copy(b.Bytes(), "hello")
	fmt.Printf("%s\n", b.Bytes()[:5])
	b.Free()

	NewBuffer(4096) // forgotten, never freed explicitly
	runtime.GC()
	time.Sleep(10 * time.Millisecond)
	fmt.Println("end of main")
}
malloc 1024 bytes at 0x25693270
hello
free 0x25693270
malloc 4096 bytes at 0x25694040
free 0x25694040
end of main

The same shape works for file descriptors, sockets, GPU buffers, database handles from a C library, or a slot in your own pool: the wrapper holds the resource, AddCleanup gets the raw resource as arg, and Close releases it explicitly and calls Stop.

A few things to watch for:

Choosing a tool

Need Use
Release a resource deterministically an explicit Close, called with defer
Release it as a safety net if Close is forgotten runtime.AddCleanup, with Stop in Close
Keep an object alive until a C call or syscall finishes runtime.KeepAlive
Refer to an object without keeping it alive weak.Make and Value
Share live values by key without pinning them a map of weak.Pointer plus AddCleanup to remove entries
Deduplicate equal values unique.Make
Reuse temporary objects sync.Pool
New code that would use runtime.SetFinalizer runtime.AddCleanup instead

And the mistakes to avoid:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents