Java中finalize方法的等价物

huangapple go评论72阅读模式
英文:

Equivalent of java finalize method

问题

在Go语言中是否有类似Java中的finalize方法?如果我有一个类似下面的结构体类型:

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

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

我该如何确保当对象被垃圾回收时,文件会被关闭?

英文:

Is there any method like java finalize in 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?

答案1

得分: 16

你在Java中也不会这样做。在Java中正确的做法是在打开的地方附近有一个finally块来关闭它。

在Go中,你可以使用defer函数来进行清理,类似的模式。例如,如果你在Java中这样做:

try {
  open();
  // 做一些操作
} finally {
  close();
}

在Go中,你可以这样做:

open();
defer close();
// 做一些操作
英文:

You wouldn't do that in java, either. The correct thing to do in java is to have a finally block that closes it somewhere near where you opened up.

You'd use a similar pattern in go with a defer function to do the cleanup. For example, if you did this (java):

try {
  open();
  // do stuff
} finally {
  close();
}

In go, you'd do this:

open();
defer close();
// do stuff

答案2

得分: 7

runtime.SetFinalizer据我所知。但这被认为是一件不好的事情,并不能保证在程序退出之前运行。

编辑:如下所述,当前的os包已经在文件上调用了runtime.SetFinalizer。然而,不应该依赖SetFinalizer。举个例子,我有一个类似文件服务器的应用程序,在那里我忘记关闭打开的文件。在垃圾回收器将它们拾起并调用它们的终结器之前,该进程通常会打开大约300个文件。

英文:

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.

huangapple
  • 本文由 发表于 2011年1月9日 07:40:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/4636817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定