[英]Will un-close resources auto-close by gc in java or other gc-lang? and why
諸如 fileInputStream 之類的資源未關閉。 gc清理時會關閉嗎? 為什么或為什么不呢?
指的是: Java中的finalize()方法是什么時候調用的?
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,所以應該不能依賴。 您應該始終關閉流以防止內存泄漏,即使底層垃圾收集可能會為您處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.