Java中最终化的目的是什么? [英] What is the purpose of finalization in Java?

查看:120
本文介绍了Java中最终化的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对最终化的理解是:

为了清理或回收对象占用的内存,垃圾收集器开始运行。 (自动被调用?)

To clean up or reclaim the memory that an object occupies, the Garbage collector comes into action. (automatically is invoked?)

垃圾收集器然后取消引用该对象。有时,垃圾收集器无法访问该对象。然后调用finalize进行最后的清理处理,之后可以调用垃圾收集器。

The garbage collector then dereferences the object. Sometimes, there is no way for the garbage collector to access the object. Then finalize is invoked to do a final clean up processing after which the garbage collector can be invoked.

这是否是对finalization的准确描述?

Is this an accurate description of finalization?

推荐答案

垃圾收集器在后台自动运行(虽然它可以被显式调用,但对此的需求应该很少)。它基本上只清理其他对象没有引用的对象(授予,完整的图片更复杂,但这是基本的想法)。因此它不会更改任何活动对象中的任何引用。如果无法从任何活动对象访问对象,这意味着可以安全地进行垃圾回收。

The garbage collector is working automatically in the background (although it can be explicitly invoked, but the need for this should be rare). It basically cleans up only objects which are not referenced by other objects (granted, the full picture is more complicated, but this is the basic idea). So it does not change any references in any live objects. If an object can not be accessed from any live object, this means that it can be safely garbage collected.

完成 意味着清理对象获取的资源(不是内存,而是其他资源,例如文件句柄,端口,数据库连接等)。然而,它并没有真正解决: - (

Finalization was meant to clean up resources acquired by the object (not memory, but other resources, e.g. file handles, ports, DB connections etc.). However, it did not really work out :-(


  • finalize()将被称为

  • 事实上,无法保证将永远调用 finalize()

  • it is unpredictable when finalize() will be called
  • in fact, there is no guarantee that finalize() will be called ever!

因此,即使保证被调用,它也不是释放资源的好地方:当它被调用以释放所有资源时您打开的数据库连接,系统可能已完全用完了免费连接,并且您的应用程序不再有效。

So even if it were guaranteed to be called, it would not be a good place to release resources: by the time it is called to free up all the DB connections you have opened, the system may have run out of free connections completely, and your app does not work anymore.

这篇关于Java中最终化的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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