Reputation: 71
A resource such as a fileInputStream, was not close. Will it be closed when gc clean it? and why or why not?
Upvotes: 1
Views: 64
Reputation: 29680
Refers to: When is the finalize() method called in Java?
FileInputStream
overrides Object#finalize
, as seen below:
/**
* 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();
}
}
When FileInputStream#finalize
is called, FileInputStream#close
will be called with it (under certain conditions). However, Object#finalize
has been deprecated in Java 9, so it should not be relied upon. You should always close your streams to prevent memory leaks, even if the underlying garbage collection may handle it for you.
Upvotes: 1