谷歌去相当于Java finalize方法 [英] google go equivalent of java finalize method

查看:111
本文介绍了谷歌去相当于Java finalize方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有像java中的finalize方法在Google中去?如果我有一个像

类型的结构体

  type Foo struct {
f * os.File
.. ..
}

func(p * Foo)finalize(){
pfclose()
}

如何确保当Object被垃圾收集时,文件已关闭?

解决方案

runtime.SetFinalizer iirc。但它被认为是一件坏事,并不保证在程序退出前运行。编辑:如下所述,当前 os 包已经在文件上调用了 runtime.SetFinalizer 。但是,不应该依赖 SetFinalizer 。举个例子,我有一个类似文件服务器的应用程序,我忘记关闭打开的文件。这个过程通常会在GC收到它们并调用它们的终结器之前打开大约300个文件。


Is there any method like java finalize in google go? If I've a type struct like

    type Foo struct {
        f *os.File
        ....
    }

func (p *Foo) finalize() {
     p.f.close( )           
}

How can I make sure that when Object is garbage collected, the file is closed?

解决方案

runtime.SetFinalizer iirc. But its considered a bad thing and isn't guaranteed to run before program exit

EDIT: As mentioned below, the current os package already calls runtime.SetFinalizer on files. However, SetFinalizer shouldn't be relied upon. As an example of why, I had a file-server-like application where I forgot to close open file. The process would usually get to about 300 open files before the GC picked them up and called their finalizer.

这篇关于谷歌去相当于Java finalize方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆