gpt4 book ai didi

java - java或其他gc-lang中的gc会自动关闭未关闭的资源吗?以及为什么

转载 作者:行者123 更新时间:2023-11-30 06:18:48 25 4
gpt4 key购买 nike

诸如 fileInputStream 之类的资源未关闭。 gc clean后会关闭吗?为什么或为什么不?

最佳答案

引用:When is the finalize() method called in Java?

FileInputStream 覆盖 Object#finalize,如下所示:

/**
* Ensures that the <code>close</code> method of this file input stream is
* called when there are no more references to it.
*
* @deprecated The {@code finalize} method has been deprecated.
* Subclasses that override {@code finalize} in order to perform cleanup
* should be modified to use alternative cleanup mechanisms and
* to remove the overriding {@code finalize} method.
* When overriding the {@code finalize} method, its implementation must explicitly
* ensure that {@code super.finalize()} is invoked as described in {@link Object#finalize}.
* See the specification for {@link Object#finalize()} for further
* information about migration options.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FileInputStream#close()
*/
@Deprecated(since="9")
protected void finalize() throws IOException {
if ((fd != null) && (fd != FileDescriptor.in)) {
/* if fd is shared, the references in FileDescriptor
* will ensure that finalizer is only called when
* safe to do so. All references using the fd have
* become unreachable. We can call close()
*/
close();
}
}

当调用FileInputStream#finalize时,FileInputStream#close将随之调用(在某些条件下)。但是,Object#finalize 在 Java 9 中已被弃用,因此不应依赖它。您应该始终关闭流以防止内存泄漏,即使底层垃圾收集可以为您处理它。

关于java - java或其他gc-lang中的gc会自动关闭未关闭的资源吗?以及为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com