在垃圾回收期间何时调用finalize()? [英] When is finalize() invoked during garbage collection?

查看:78
本文介绍了在垃圾回收期间何时调用finalize()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发件人:

> https://www.baeldung.com/java-memory的Q11-management-interview-questions

当某个对象符合使用GC的条件时,垃圾收集器必须在其上运行finalize();此方法保证只能运行一次,因此收集器将对象标记为已完成,并让它休息直到下一个周期.

我有几个问题要问:

  • 那句话正确吗?
  • 是在标记阶段,垃圾收集器是否调用finalize()方法?
  • 为什么要休息直到下一个周期?

P.S:我确实知道在Java 9中最终不推荐使用finalize().这要归功于优秀的灵魂,他决定这么做.

P.S: I do understand that finalize() is finally deprecated in Java 9. Thanks to good soul who decided to make it so.

推荐答案

是在标记阶段,垃圾收集器会调用finalize()方法吗?

Is it during the marking phase, does the garbage collector invoke the finalize() method?

依赖于实现,但通常没有.GC完成后,终结器由后台线程调用.

Implementation dependent, but generally no. The finalizer is called by a background thread after GC completes.

请记住,GC可能是世界停止的事件,应尽可能短.终结器方法可能很慢,因此不应在GC中调用它们.

Remember, GC may be a stop-the-world event, and should be as short as possible. Finalizer methods may be slow, so they should not be called during GC.

为什么要休息直到下一个周期?

Why does it give a rest until the next cycle?

在较高级别(简化)下,它的操作如下(请参见

At a high level (simplified), it operates as follows (see JLS 12.6.1 for terms):

  • GC检测到无法到达 的对象:

  • 如果对象具有终结器方法,请将其添加到终结器队列.
    该对象是 finalizable .

如果从 finalizable 对象可以访问该对象,则将其保留.
该对象是 finalizer-reachable .

If the object is reachable from an finalizable object, leave it.
The object is finalizer-reachable.

否则立即回收内存.
该对象是不可达.

Background Finalizer线程进程排队的 finalizable 对象:

Background Finalizer thread processes queued finalizable objects:

  • 调用 finalize()方法.
    当方法返回时,对象被完成.

因为GC已经完成,所以最终完成的对象将处于静止状态",直到下一个GC周期为止.

Since GC has already completed, finalized objects are "resting" until next GC cycle.

在下一个GC周期中,带有终结器方法且标记为 finalized 的对象被视为 unreachable ,并且将回收内存(假定finalizer方法没有再次使对象可达).

On next GC cycle, objects with a finalizer method that is marked finalized is treated as unreachable, and memory will be reclaimed (assuming finalizer method didn't make the object reachable again).

请注意,对象可完成时可能会发生许多GC周期,即,终结器线程可能需要一段时间才能处理该对象.

Note that many GC cycles may occur while an object is finalizable, i.e. it may take a while for the Finalizer thread to process the object.

这篇关于在垃圾回收期间何时调用finalize()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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