GC和Finalizer

GC和Finalizer

最近在做一个golang的连接池。测试过程中发现一个有趣的现象,获取的连接没有归还给连接池,那么过一段时间后该连接会自动关闭掉。猜测这跟连接池应该是没有关系的,于是再用普通的连接做了实验,即dial一个tcp连接,发送请求,然后程序进入sleep,一段时间后该连接还是会自动关闭。

对这个过程进行抓包分析,发现主动关闭连接的是client端,即client端主动向服务端发送了FIN包。

考虑到golang有垃圾回收机制,如果该连接被程序引用着怎么办?是否也会自动关闭?想想这应该是不可能的,那这是不是跟垃圾回收有关系?!

对程序稍作改动,在发送完第一个请求之后,保留该连接的reference不释放,进入sleep。观察一段时间,无论过多久,netstat查看该连接都是ESTABLISHED状态的。

因此猜测这肯定跟GC有关系。

果然,在stackoverflow上发现golang的GC也会执行一个”Finalizer”的过程,跟Java类似。如果对象使用SetFinalizer()设置了Finalizer函数的话。默认情况下,有些对象是自动设置了Finalizer的:

  • os.File: The file is automatically closed when the object is garbage collected.

  • os.Process: Finalization will release any resources associated with the process. On Unix, this is a no-operation. On Windows, it closes the handle associated with the process.

  • net.netFD: it appears that package net can automatically close a network connection.

    同时,写了另一个小程序以看效果。
package main

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

type Object struct {
    Id string
}

func (o *Object) Close() {
    fmt.Printf("(%T)<%+v> is closing, closing, closing\n", o, o)
}

func NewObject() *Object {
    obj := &Object{Id: "123"}
    runtime.SetFinalizer(obj, (*Object).Close)
    return obj
}

func main() {
    fmt.Println("hello world.")

    run()

    runtime.GC()
    time.Sleep(3 * time.Second)
}

func run() {
    o := NewObject()
    fmt.Println(o)
}

在这,我手动触发了gc,返回结果:

main.go:24- hello world.
main.go:34- &{123}
main.go:14- (*main.Object)<&{Id:123}> is closing, closing, closing

—END—

Spread the love
Comments are closed.