简体   繁体   English

Finalize()清理与垃圾收集器从内存中删除对象

[英]Finalize() cleanup vs. Garbage Collector removing an object from memory

I was reading about the finalize() method and was curious: 我正在阅读有关finalize()方法的内容并且很好奇:

What is the difference between the task of cleaning up objects ( setting them to NULL ) in finalize, and removing an object from memory? 在finalize中清理对象(将它们设置为NULL)和从内存中删除对象的任务有什么区别?

What is the difference between the task of cleaning up objects ( setting them to NULL ) in finialize 在finialize中清理对象(将它们设置为NULL)的任务之间有什么区别

setting to null removes ONE reference to the object. 设置为null将删除对该对象的ONE引用。 if NO more references to an object exists, the garbage collector is allowed (not required) to remove the object 如果存在对对象的更多引用,则允许(不要求)垃圾收集器移除该对象

and removing an object from memory? 并从内存中删除对象?

there is NO explicit way in java to remove (destroy, delete) an object. 在java中没有明确的方法来删除(销毁,删除)一个对象。 The garbage collector will do it when he likes. 垃圾收集器会在他喜欢的时候做。 Especially the time from removing the last reference to remove/destroy the object is indefinite 特别是从删除最后一个引用到删除/销毁对象的时间是不确定的

There is NO need to set references to null in finalize method. 没有必要设置引用为的finalize方法。 when the garbage collector call finalize the objects and its references will gone soon anyway. 当垃圾收集器调用完成对象时,无论如何它的引用都会很快消失。

I never wrote an own finalize method during my very long java experience. 在我很长的java体验中,我从未编写过自己的finalize方法。

The rare occasion in which it make sense to wrote an own finalize method appear if your object is dealing with os-resources. 如果您的对象正在处理os资源,则会出现编写自己的finalize方法有意义的罕见场合。 However, in general you use standard packages for os accesss 但是,通常您使用标准包进行操作系统访问

You don't "clean up" an object when you set it to null , you're just setting the reference to null, consider: 将对象设置为null ,不要“清理”对象,只需将引用设置为null,请考虑:

Object a = new Object();
Object b = a;
a = null;
System.out.println(b);

Once an object loses all references, it will be collected on the next GC pass. 一旦对象丢失所有引用,它将在下一次GC传递时收集。 Finalize is a method that gets called when this happens, and you should avoid using it . Finalize是一种在发生这种情况时被调用的方法, 你应该避免使用它

Just don't keep extra references around and let the GC do it's job. 只是不要保留额外的参考,让GC做它的工作。

finalize() is called by garbage collector when an object has no more references. 当对象没有更多引用时,垃圾收集器调用finalize()。 You can override it and best practice is to use it in a try-catch-finally block to free non java resources like files. 你可以覆盖它,最好的做法是在try-catch-finally块中使用它来释放非java资源,比如文件。 Anyway if you use it this way you should also call super.finalize() to ensure class hierarchy finalization. 无论如何,如果你以这种方式使用它,你也应该调用super.finalize()来确保类层次结构的最终化。

This method is always for advanced use and shouldn't be used in normal production code. 此方法始终是高级用法,不应在正常的生产代码中使用。 Free your resources in finally clauses in methods using those resources. 在使用这些资源的方法的finally子句中释放资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM