Skip to content

runtime: SetFinalizer causes undesirable memory overhead #45581

@zhangqiang-01

Description

@zhangqiang-01

What version of Go are you using (go version)?

$ go version
go version go1.15.1 linux/amd64

Does this issue reproduce with the latest release?

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE="auto"
GOARCH="amd64"
GOBIN=""
GOCACHE="/root/.cache/go-build"
GOENV="/root/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/root/gosrc/pkg/mod"
GONOPROXY="code.byted.org"
GONOSUMDB="code.byted.org"
GOOS="linux"
GOPATH="/root/gosrc/"
GOPRIVATE="code.byted.org"
GOPROXY="https://go-mod-proxy.byted.org,https://goproxy.cn,direct"
GOROOT="/root/go"
GOSUMDB="sum.golang.google.cn"
GOTMPDIR=""
GOTOOLDIR="/root/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build392013595=/tmp/go-build -gno-record-gcc-switches"

What did you do?

package main

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

type A struct {
	buf []byte
}

func finalize(a interface{}) {
}

func test(wg *sync.WaitGroup) {
	for i := 0; i < 100000; i++ {
		for j := 0; j < 100000; j++ {

			a := &A{
				buf: make([]byte, 1024*1024),
			}
			runtime.SetFinalizer(a, finalize)

		}
		time.Sleep(time.Microsecond)
	}

	wg.Done()
}

func main() {
	n := 100
	wg := &sync.WaitGroup{}
	wg.Add(n)
	
	for i := 0; i < n; i++ {
		go test(wg)
	}

	wg.Wait()
}

What did you expect to see?

I want the process to consume less memory.

What did you see instead?

Use SetFinalizer:
Actual memory usage 101GB
VmRSS: 106328688 kB

Unuse SetFinalizer:
Actual memory usage 4.5GB
VmRSS: 5481500 kB

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.WaitingForInfoIssue is not actionable because of missing required information, which needs to be provided.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions