Soft Memory Limit With debug.SetMemoryLimit

Cap the Go runtime with debug.SetMemoryLimit: read the previous limit, set a soft ceiling, and restore it without a hard crash.

GoResilience

Code

gosnippet
18 lines
package main

import (
	"fmt"
	"runtime/debug"
)

func main() {
	// soft memory limit:软上限让 GC 更努力回收,而不是像硬上限那样崩溃
	prev := debug.SetMemoryLimit(32 << 20)
	fmt.Println("default limit was:", prev)

	// 传 -1 只读取当前值,不修改
	fmt.Println("current limit:", debug.SetMemoryLimit(-1))

	debug.SetMemoryLimit(prev) // 用完恢复,不影响宿主进程
	fmt.Println("restored:", debug.SetMemoryLimit(-1))
}

The runtime story

Everything happens inside the function main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The signature at the center: func main()

The demo output is labeled (default limit was:, current limit:, restored:), so the output doubles as a step-by-step trace of what the file did.

Key statements

func main() {
// soft memory limit:软上限让 GC 更努力回收,而不是像硬上限那样崩溃
prev := debug.SetMemoryLimit(32 << 20)
fmt.Println("default limit was:", prev)
// 传 -1 只读取当前值,不修改
fmt.Println("current limit:", debug.SetMemoryLimit(-1))
debug.SetMemoryLimit(prev) // 用完恢复,不影响宿主进程
fmt.Println("restored:", debug.SetMemoryLimit(-1))
}

Interactive Tools for This Topic

FAQ

What does Soft Memory Limit With debug.SetMemoryLimit print when run?
Execute the whole file; each printed line is prefixed with a label like `default limit was:`, `current limit:`, `restored:`.