java gc与finalize,Java中System.gc()和finalize()方法之间有什么区别?

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() kindly asks the sytem to perform a garbage collection. Javadoc says:

Runs the garbage collector.

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() 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.

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

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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值