java 为什么不调用 finalize?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7786946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is finalize not being called?
提问by prap19
I have couple of questions regarding garbage collector in java.
我有几个关于 java 中的垃圾收集器的问题。
Q1.As far as I understand, finalize() gets called when object is out of scope and JVM is about to collect garbage. I thought finalize() method is called automatically by garbage collector, but it does not seems to work in this case. What is the explanation? Why is the need for me to explicitly call finalize() method?
Q1.据我所知,当对象超出范围并且JVM即将收集垃圾时,会调用finalize()。我认为垃圾收集器会自动调用 finalize() 方法,但在这种情况下它似乎不起作用。解释是什么?为什么我需要显式调用 finalize() 方法?
public class MultipleConstruct {
int x,y;
public MultipleConstruct(int x)
{
this.x= x;
y=5;
System.out.println("ONE");
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
System.out.println("FINALIZED");
}
public static void main(String[] args) throws Throwable {
MultipleConstruct construct = new MultipleConstruct(3);
}
}
Q2. Also, when is garbage collector invoked? I understand gc is a daemon thread and invoked by JVM depending on heap size remaining. Does that mean, JVM waits for the program to use threshold limit of resources and then notify the gc to sweep garbage objects.
Q2。另外,什么时候调用垃圾收集器?我知道 gc 是一个守护线程,由 JVM 根据剩余的堆大小调用。这是否意味着,JVM 等待程序使用资源的阈值限制,然后通知 gc 清扫垃圾对象。
EDIT:How does gc resolved circular references?
编辑:gc 如何解决循环引用?
采纳答案by Jatin
There is a lot to finalize() method which is frankly a lot to write, but in short:
finalize() 方法有很多,坦率地说有很多要写,但简而言之:
An object is in the finalized state if it is still unreachable after its finalize method, if any, has been run. A finalized object is awaiting deallocation. Note that the VM implementation controls when the finalizer is run. You are almost always better off doing your own cleanup instead of relying on a finalizer. Using a finalizer can also leave behind critical resources that won't be recovered for an indeterminate amount of time.
如果对象在其 finalize 方法(如果有)运行后仍然无法访问,则该对象处于 finalized 状态。一个最终的对象正在等待释放。请注意,VM 实现控制何时运行终结器。您几乎总是最好自己进行清理而不是依赖终结器。使用终结器还会留下在不确定的时间内无法恢复的关键资源。
In your case the reason it does not print is that you do not know when the finalizer thread will call the finalize() method. What is happening is that the program is terminating before anything can get printed. To check it: edit the code inside main code by( NOTE: this does not guarrantee nor should you should ever rely on it but still it does prints some time)
在您的情况下,它不打印的原因是您不知道终结器线程何时会调用 finalize() 方法。正在发生的事情是程序在打印任何内容之前终止。要检查它:编辑主代码中的代码(注意:这不保证也不应该依赖它,但它仍然会打印一些时间)
for(int i =0;i<1000000;i++)
{
MultipleConstruct construct = new MultipleConstruct(3);
construct = null;
}
There are a lot of disadvantages of using a finalize() right from taking more time in object construction to possibility of memory leakage and memory starvation. If you strongly refer to the same object inside the finalize() then it is never called the second time and thus can leave system in undesired state etc etc etc... The only place where you should use finalize() is as a safety net to dispose any resources like InputStream uses it to close (which again there is no guarrantee that it will will br run when your program is still alive). Another place to use it is while using natives where garbage collector has no control.
使用 finalize() 有很多缺点,从在对象构造中花费更多时间到内存泄漏和内存不足的可能性。如果你在 finalize() 中强烈引用同一个对象,那么它永远不会被第二次调用,因此会使系统处于不希望的状态等等等等......你应该使用 finalize() 的唯一地方是作为一个安全网处理任何资源,如 InputStream 使用它来关闭(这再次没有保证它会在您的程序还活着时运行)。另一个使用它的地方是使用本地垃圾收集器无法控制的地方。
For more info visit:
欲了解更多信息,请访问:
回答by fpacifici
q1) finalize method is called when the object is being garbage collected, thus, if no GC is being performed, your finalizer may not be called. You need to call super simply to preserve the behavior provided by Object implementation.
q1) finalize 方法在对象被垃圾回收时被调用,因此,如果没有 GC 正在执行,你的终结器可能不会被调用。您只需调用 super 即可保留 Object 实现提供的行为。
q2) the exact moment in which GC is performed depends on a lot of factors like: which JVM you are using, tuning parameters, amount of free heap, etc. So it does not only rely on a used heap threshold. You can also ask for a GC to be performed through System.gc() but you have no guarantee about if and when it will be actually executed. You can find some details on how to configure GC in http://java.sun.com/performance/reference/whitepapers/tuning.html
q2) GC 执行的确切时刻取决于很多因素,例如:您使用的 JVM、调整参数、空闲堆的数量等。因此它不仅仅依赖于已使用的堆阈值。您还可以通过 System.gc() 要求执行 GC,但您不能保证是否以及何时实际执行。您可以在http://java.sun.com/performance/reference/whitepapers/tuning.html 中找到有关如何配置 GC 的一些详细信息
回答by ratchet freak
it gets called eventuallyor not at all
它最终被调用或根本不调用
basically the GC scans the heap for everything that is not reachable and runs the finalizer on those (after which it needs to prove again it is not reachable for it to be freed)
基本上,GC 会扫描堆中所有无法访问的内容,并在这些内容上运行终结器(之后它需要再次证明它无法访问以释放它)
however it can take a while (effectively undefined and actually dependent on program behavior) for the GC to find it which is why you shouldn't really rely on it to dispose of critical data
然而,GC 可能需要一段时间(实际上未定义并且实际上取决于程序行为)才能找到它,这就是为什么您不应该真正依赖它来处理关键数据
edit: as for circular references it distinguishes between objects with a finalize method and objects without one
编辑:至于循环引用,它区分具有终结方法的对象和没有终结方法的对象
for an object to be freed (deleted from main memory) it may not be reachable by any code (this includes finalizers that still need to run)
对于要释放的对象(从主内存中删除),它可能无法被任何代码访问(这包括仍需要运行的终结器)
when 2 objects with finalizers are eligible to get the finalizers run the GC arbitrarily selects one object and runs the finalizer on it and then it can run the other object
当 2 个带有终结器的对象有资格让终结器运行时,GC 任意选择一个对象并在其上运行终结器,然后它可以运行另一个对象
note that a finalizer can run while the fields of the objects may or may not be finalized already
请注意,终结器可以运行,而对象的字段可能已经完成,也可能尚未完成
回答by anurag11
finalize() method is called automatically during garbage collection. System.gc() method forcibly calls garbage collector. but we will have to destroy object before. example:
在垃圾回收期间会自动调用 finalize() 方法。System.gc() 方法强制调用垃圾收集器。但我们必须先销毁对象。例子:
public class Sample
{
public Sample()
{
System.out.println("Object created");
}
@Override
public void finalize()
{
System.out.println("Object Destroyed");
}
public static void main(String args[])
{
Sample x=new Sample();
Sample y=new Sample();
x=null;
y=null;
System.gc();
}
}