1.3 runtime.AddCleanup 与 weak 包
适用版本:Go 1.24+;本次复核使用 Go 1.27.0,darwin/arm64。每个完整示例分别保存为 main.go,用 go run main.go 执行,不需要外部依赖。
本节先区分三件事:显式关闭资源、取消回收回调、观察对象回收。GC 回调只适合作为补充机制,文件或连接仍应按正常生命周期显式关闭。
1.3.1 取消能力与执行边界
SetFinalizer(obj, nil) 可以清除对象关联的 finalizer,因此「finalizer 无法取消」是不准确的。AddCleanup 则返回独立的 Cleanup 句柄。
| 比较项 | SetFinalizer | AddCleanup |
|---|---|---|
| 注册关系 | 对象关联一个 finalizer | 对象可注册多个 cleanup |
| 清除方式 | SetFinalizer(obj, nil) | Cleanup.Stop() |
| 回调收到什么 | 对象本身 | 独立参数 arg |
| 退出前是否保证执行 | 不保证 | 不保证 |
Stop() 不能撤回已经排队的 cleanup。若要保证取消,应让原对象在 Stop() 调用期间保持可达。参数或闭包引用原对象也可能阻止回收。
1.3.2 观察 cleanup:等待结果,不承诺回收时间
下面的对象包含 64 字节数组,避免把演示建立在无指针小对象的批量分配行为上。回调通过通道通知主程序;超时只是「本次没有观察到」,不代表 API 失效。
package main
import (
"fmt"
"runtime"
"time"
)
type resource struct{ data [64]byte }
// 返回后局部变量不再被主程序持有。
func register(done chan<- string) {
r := new(resource)
runtime.AddCleanup(r, func(id int) {
done <- fmt.Sprintf("cleanup ran for resource %d", id)
}, 7)
runtime.KeepAlive(r)
}
func main() {
done := make(chan string, 1)
register(done)
runtime.GC()
select {
case result := <-done:
fmt.Println(result)
case <-time.After(2 * time.Second):
fmt.Println("cleanup not observed within 2s")
}
}
本次执行输出:
cleanup ran for resource 7
1.3.3 Stop:在对象仍可达时取消
package main
import (
"fmt"
"runtime"
"time"
)
type resource struct{ data [64]byte }
func cancel(done chan<- struct{}) {
r := new(resource)
cleanup := runtime.AddCleanup(r, func(_ int) { done <- struct{}{} }, 7)
cleanup.Stop()
runtime.KeepAlive(r) // 保证对象在 Stop 调用期间仍可达
}
func main() {
done := make(chan struct{}, 1)
cancel(done)
runtime.GC()
select {
case <-done:
fmt.Println("unexpected cleanup")
case <-time.After(100 * time.Millisecond):
fmt.Println("cleanup not observed after Stop")
}
}
本次执行输出:
cleanup not observed after Stop
有限等待不能单独证明未来绝不会调用;取消保证来自 API 合约与对象可达性条件,输出只是这次执行的观察。
1.3.4 weak:不延长对象寿命
package main
import (
"fmt"
"runtime"
"weak"
)
type payload struct{ data [64]byte }
func makeWeak() weak.Pointer[payload] {
p := new(payload)
w := weak.Make(p)
fmt.Println("while reachable:", w.Value() != nil)
runtime.KeepAlive(p)
return w
}
func main() {
w := makeWeak()
for i := 0; i < 5; i++ {
runtime.GC()
}
fmt.Println("nil observed after GC:", w.Value() == nil)
}
本次执行输出:
while reachable: true
nil observed after GC: true
不应据此承诺「固定几次 GC 后必然返回 nil」。零大小对象及无指针小对象有特殊边界。弱引用缓存仍需要清理失效键,并在使用 Value() 返回的强引用期间保持它可达。
1.3.5 自行核验版本与文档
使用当前工具链定位,避免假设 Go 固定装在 /usr/local/go:
go version
go doc runtime.SetFinalizer
go doc runtime.AddCleanup
go doc runtime.Cleanup.Stop
go doc weak.Pointer.Value
rg 'AddCleanup|pkg weak,' "$(go env GOROOT)/api/go1.24.txt"
API 清单可核对引入版本,不能证明所有后续版本行为完全一致。跨版本结论需要分别执行并保存结果。
1.3.6 练习与检查点
- 把
KeepAlive(r)移到Stop()之前,解释为什么这不再保证整个取消调用期间可达。 - 将弱引用对象改成零大小结构体,观察输出是否稳定。答案应是「不能依赖一定被回收」,而不是写固定输出断言。
- 设计连接的显式
Close()路径,说明为何 GC 回调不应承担事务提交或缓冲区落盘。
官方依据与修订记录
- runtime.SetFinalizer :清除关联回调及生命周期条件。
- runtime.Cleanup.Stop :取消条件。
- weak.Pointer :弱引用及特殊分配边界。
2026-10-12:更正取消能力,补齐可达性条件;替换小对象实验并独立复跑以上三个完整程序。输出仅描述记录环境中的观察,不推广为 GC 时限保证。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。