Java中System.gc()和finalize()方法之间有什么区别? [英] What is difference between System.gc() and finalize() method in java?

查看:225
本文介绍了Java中System.gc()和finalize()方法之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java的system.gc()和finalize()方法之间感到困惑. 我们不能强行将垃圾对象收集到JVM.我们允许在我们的Java代码中编写这两个方法,然后,如果这两个方法都用于垃圾回收,那么为Java提供两种垃圾回收方法又有什么意义呢?

I am confuse in between system.gc() and finalize() method of java. We can't force to collect garbage object to JVM. We are allow to write both methods in our java code then if both are used for garbage collection, then what is point in providing two methods for garbage collection by java?

请告诉我这两种方法的确切工作原理以及内部的工作原理?

Please tell me the exact working of both methods and internally how it works?

推荐答案

System.gc()恳请系统执行垃圾回收. Javadoc说:

System.gc() kindly asks the sytem to perform a garbage collection. Javadoc says:

运行垃圾收集器.

Runs the garbage collector.

您无法控制垃圾收集器的工作强度.垃圾收集器内部的工作方式是特定于VM的,它本身就是一个研究主题.但是通常会有完整的"垃圾收集和一些较小的增量"收集.因此,请考虑将System.gc作为请求,但不能保证将对对象进行垃圾回收.

You can not control how "hard" the garbage collector will work. How the garbage collector work internally is VM-specific and a research topic on its own. But there are usually "full" garbage collection and some smaller "incremental" collection going on. So consider System.gc as a request, but there's not guaranteed that garbage collection of your object will happen.

Object.finalize()来指定垃圾回收给定对象时的操作(实际上是垃圾回收之前的操作). Javadoc说:

Object.finalize() can be overriden to specify what to do when a given object is garbage collected (actually what to do just before it is garbage collected). Javadoc says:

在垃圾回收时由垃圾回收器在对象上调用 确定不再有对该对象的引用.

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

finalizer的经典用法是在垃圾回收对象(例如,垃圾回收)时释放系统资源.释放文件句柄,临时文件等.

Classical use of finalizer are to de-allocate system resources when an object is garbage collected, e.g. release file handles, temporary files, etc.

当JVM退出时,请勿使用终结器执行操作.为此,请使用在Runtime.getRuntime().addShutdownHook(Thread)中注册的关闭钩子.

Do not use finalizer to perform actions when the JVM exits. For this purpose use a shutdown hook that you register with Runtime.getRuntime().addShutdownHook(Thread).

这篇关于Java中System.gc()和finalize()方法之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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